-1

How would you make a Java program terminate itself when 'ESCAPE' is pressed? I have tried this:

   public class Main {

   public static final int i = 12;

   public static void Exit(KeyEvent e) {

    if (e.getKeyCode() == 27)
    {
        System.exit(0);
    System.out.println("Closing");
    }

}

public static void main (String args[]) {

    while(i <= 0) {
        Exit(null);
    }

   }
}

However, it does not appear to work. Any suggestions?

None None
  • 147
  • 2
  • 3
  • 11
  • 1
    If you want to process individual key strokes, create a Swing GUI. There are great tutorials available online that Google can help you find. – Hovercraft Full Of Eels May 25 '13 at 23:09
  • See this http://stackoverflow.com/questions/16381879/how-to-process-the-backspace-terminal-control-character-in-java –  May 25 '13 at 23:10

3 Answers3

1
while(i <= 0) {
    ...
}

and i is initialized as 12. This will never enter the loop unless you change i value to something less than or equal 0.

Lucia Pasarin
  • 2,268
  • 1
  • 21
  • 37
0

Some options:

  • Use System.exit(0).
  • All non-deamon threads are finished.

If this is a swing application, then use key-bindings instead of key listeners, and you can depend on the JFrame's X button to terminate the application (where you'd use frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)).

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • I actually can't use this, as when the program starts all buttons become "un-pressable" due to the program constantly looping. This is why I need a key to close the program when pressed. – None None May 26 '13 at 02:03
0

I could figure out only two way to intercept keys in java.

  1. If you want to do it for a standalone java application then you will have to do it natively, using JNI.You can google to find out the C/C++ libraries to intercept keys . And then you can load the dlls in java to help you with your requirement.

  2. If you are writing a SWING based GUI then you can add keypress lisenter to your components. You may have to add it to all the components recursively to intercept the key at any level of your UI. Here is a sample code for that:

Add key listener to a components and its children using a method:

private void addKeyAndContainerListenerRecursively(Component c)
     {
//Add KeyListener to the Component passed as an argument
          c.addKeyListener(this);
//Check if the Component is a Container
          if(c instanceof Container) {
//Component c is a Container. The following cast is safe.
               Container cont = (Container)c;
//Add ContainerListener to the Container.
               cont.addContainerListener(this);
//Get the Container's array of children Components.
               Component[] children = cont.getComponents();
//For every child repeat the above operation.
               for(int i = 0; i < children.length; i++){
                    addKeyAndContainerListenerRecursively(children[i]);
               }
          }
     }

Method to do get the key press event:

  public void keyPressed(KeyEvent e)
     {
          int code = e.getKeyCode();
          if(code == KeyEvent.VK_ESCAPE){
//Key pressed is the Escape key. Hide this Dialog.
               setVisible(false);
          }
          else if(code == KeyEvent.VK_ENTER){
//Key pressed is the Enter key. Redefine performEnterAction() in subclasses 
to respond to pressing the Enter key.
               performEnterAction(e);
          }
//Insert code to process other keys here
     }

Hope it helps!

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • I tried using this, but I got a NullPointerException. I originally had an 'exit' button that terminated the program, but once the person presses the 'start' button it enters into an infinite loop, which causes the 'start' button to be pressed in constantly and making the user unable to use the red 'X' button or the 'exit' button. However, due to the loop being in an ActionListener for the button I am unable to use KeyEvent. I am not the newest to programming, but I am definitely learning and have a lot to go. Any ideas? – None None May 26 '13 at 01:54