Question

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
}
Was it helpful?

Solution

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 JApplet is an exception to the "in general"... you normally can't call System.exit from 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.

OTHER TIPS

Probably, I think the AWT code is correct but the rest is terribly cryptic (Not that I don't understand it, but it doesn't express what you are actually doing very well, does it?)

How about:

boolean running=false;

...
if(running)
    System.exit(0);
else
    running=true;

instead?

Update: After reading your discussion on the other post, you are going to have a little strangeness.

There is this concept of the AWT thread. Everything done with the AWT must be done on that thread. So when the space bar is pressed, you will get that event on the AWT thread. You probably don't want to keep it though because as long as you hold onto it, it will prevent other graphics updates.

I suggest looking at SwingTimer Set a swing timer to notify you every few ms, and that notification will come in on the AWT thread so that you can use it to click your button, then just exit and wait for the next timer event.

When they press space bar again, system.exit() should work fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top