I am currently studying Java and I'm trying to create a screen saver program. The most important rule is not to use any loops. another key criteria is to use 'x' to exit the program and 'z' to change from fullscreen to halfscreen. My first inclination was to use setDefaultCloseOperation along with a keylistener to exit the program, but I haven't found any way to do that. can anyone please help me understand how to do this without using a loop.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ScreenSaver1 extends JPanel {
private JFrame frame = new JFrame("FullSize");
private Rectangle rectangle;
boolean full;
ScreenSaver1() {
// Remove the title bar, min, max, close stuff
frame.setUndecorated(true);
// Add a Key Listener to the frame
frame.addKeyListener(new KeyHandler());
// Add this panel object to the frame
frame.add(this);
// Get the dimensions of the screen
rectangle = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
// Set the size of the frame to the size of the screen
frame.setSize(rectangle.width, rectangle.height);
frame.setVisible(true);
// Remember that we are currently at full size
full = true;
}
// This method will run when any key is pressed in the window
class KeyHandler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
// Terminate the program.
System.exit(0);
}
}
public static void main(String[] args) {
ScreenSaver1 obj = new ScreenSaver1();
}
}
Your key handler should implement keyPressed like this:
public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == 'x') {
System.out.println("Exiting");
System.exit(0);
}
else if (e.getKeyChar() == 'z') {
System.out.println("Resizing");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With