0

How do I assign a variable to the ESC. key so that when it is pressed the program is shutdown? I am doing a calculator and the only way that I have seen is doing it directly like:

Scanner console = new Scanner(System.in); 
int x = 1;
while(x==1)
{...
System.out.println("Enter in -1 to exit program");
x = nextInt();
}

I don't know if it is possible to assign, per say a -1 to the escape key. Let me know if you have any ideas? It would be astronomically appreciated. ;-) ... :-)

Snare_Dragon
  • 59
  • 1
  • 11
  • and all of the necessary imports have been made, just to get that out of the way... – Snare_Dragon Jun 04 '17 at 18:30
  • That was it, thanks @baao my astronomical thanks goes to you!! Even though you don't get a physical trophy, and there is no use to this post thanks. :_-) – Snare_Dragon Jun 04 '17 at 18:57

2 Answers2

2

Unfortunately, you can't.

ESC can't be read by the Scanner. You are supposed to use a key listener by a UI library (for instance, Swing). Have a look at "How to write a key listener?".

In this case, you should ask for a number from a user which is a key of the loop break (like you actually did).

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

It's a long time when i used a good library, so if you can use JNativeHook library you can easily solve this problem.

Here is an example :

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class TestEscKey implements NativeKeyListener{

    @Override
    public void nativeKeyPressed(NativeKeyEvent nke) {
        if(NativeKeyEvent.getKeyText(nke.getKeyCode()).equals("Echap")){
            System.out.println("I will exit!");
            System.exit(0);
        }else{
           //do another thing
        }
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent nke) {
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent nke) {
    }

    public static void main(String[] args) throws NativeHookException {
        try {

            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            System.out.println("There was a problem registering the native hook.\n" 
                                + ex.getMessage());
            System.exit(1);
        }
        GlobalScreen.getInstance().addNativeKeyListener(new TestEscKey());
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140