0

Okay I need to make the button esc or any button stop a looping method. I've looked all over but can not find the answer. I know you can exit out of a JFrame with esc. but what about just a regular method? Any help would be great, thanks!

Maybe something like this?

    public class Stop {

    private static boolean loop = true;
    private static int x = 0;

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

        while (loop == true){

            if (esc not pressed){
                x++;
                System.out.println(x);
            }
            else{
                loop = false;
            }

        }

    }

}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Luke Worthing
  • 101
  • 1
  • 4
  • 12
  • 1
    I think you need to be in a Frame to intercept Keyboard events ... – Gauthier Boaglio Jun 13 '13 at 02:50
  • Take a look at [this example](http://stackoverflow.com/questions/17034798/how-to-kill-a-program-with-esc-or-a-button-java/17034860#17034860) which uses key bindings to register an action against the escape key – MadProgrammer Jun 13 '13 at 03:34

2 Answers2

1

You won't be able to catch key pressed events from a command line program. You need to do this from GUI features (by implementing swing's KeyListener, by example).

This seems to confirm.

Community
  • 1
  • 1
Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85
  • 1
    I'd not recommend `KeyListener` as it has focus issues (the component it is registered to must not only focusable, but have focus). For example, `JPanel` is not focusable by default. Instead you should be using [Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer Jun 13 '13 at 03:33
1

The Java console does not provide any method for getting single keystrokes. Instead, input is only read in after the enter key is pressed (i.e. for accepting characters).

One solution is to create a simple terminal-styled Swing application. This way, you can use a KeyListener to check for keyboard events, or, as you say simply hit Esc to exit the JFrame.

Alternatively, you may want to check out the Java Curses library, as I believe it offers an implementation for detecting specific keystrokes within console applications.

x4nd3r
  • 855
  • 1
  • 7
  • 20
  • 1
    I'd not recommend `KeyListener` as it has focus issues (the component it is registered to must not only focusable, but have focus). For example, `JPanel` is not focusable by default. Instead you should be using [Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer Jun 13 '13 at 03:33
  • +1, duly noted. Curses still remains a valid choice, at the cost of tying oneself down to an external library. – x4nd3r Jun 13 '13 at 03:45
  • Agreed. There's not enough context to make a valid recommendations, but within the console, I think it's the only choice I'm aware of – MadProgrammer Jun 13 '13 at 03:50