I am creating a basic screensaver for a small project for college and I am having trouble closing the JFrame after I open it. I have removed the outer panel so as to make it look a proper screensaver but I now have to open the Task Manager to close down the program, I want the window to close when I press a button on the keyboard how can I do that?
Thanks in advance.
——-EDIT——–
I have tried the first two methods given but I can’t seem to get them to work properly. Here is my code for the frame so far:
import java.awt.Color;
import javax.swing.JFrame;
public class ScreensaverTest
{
public static void main( String[] args )
{
JFrame frame = new JFrame( "Screen Saver" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setUndecorated(true);
ScreenSaverJPanel screensaverTestJPanel = new ScreenSaverJPanel();
frame.add( screensaverTestJPanel );
frame.setBackground( Color.BLACK );
frame.setVisible( true );
frame.setLocation( 0, 0 );
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
——–EDIT———
Also I am using the repaint method to move objects around the screen and I want some of them to move at different speed. I am using a random number generator for the positioning so adjusting the numbers isn’t really an option, please help.
There are a lot of examples on how to do this.
You need to add an eventListener to the frame that listens for keyboard-inputs and then closes the frame.
Try looking at this: http://www.java2s.com/Code/Java/Swing-JFC/Reacttoframecloseaction.htm
You will have to replace the event with something keyboard-related, but that is the best way to go I would think..
Edit:
To respond to the edit in the post you could do something like this:
And voila – that should work. It compiles for me on Java 7.