Say I have a GUI, and I want the program to actually run when the spacebar is pressed, but if the spacebar is pressed again then I want the program to exit. Would something like this work?
public class MouseClicker extends JApplet implements KeyListener{ int counter = 0; MouseClicker m1 = new MouseClicker(); //all of the other methods public void keyPressed( KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode==KeyEvent.VK_SPACE){ m1.click(); counter ++; if(counter%2==0) System.exit(0); } //other methods needed for KeyListener }
Try it and see 😉
Seriously though, what do you mean you want to program to run when the space bar is pressed? Unless the program is already running, how are you going to receive the
KeyEvent?As for the other half of your question, the code you have should, in general, make Java exit when the space bar is pressed. Note that there’s no point in using a counter, since as soon as Java exits, the value of the counter is lost. Also note that
JAppletis an exception to the ‘in general’… you normally can’t callSystem.exitfrom an applet, because the applet runs under the control of a browser and Java is only supposed to exit when the user closes the browser, not whenever your applet is done. There could be other applets running in the same JVM and they might not be done with what they’re doing yet.