2

I have a bot program to test my server. I would like it to exit the loop if any key was press, but do not want it to stop and wait until a key was press. thus the loop would keep running until any key on the keyboard was press.

This is how I'm trying to do it now, but does not work

        if (System.in.available()>0)
        {
            System.out.println("key pressed");
            break; // exit loop
        }
Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • you need to press enter or ctrl-d java only offers full lines – ratchet freak Apr 14 '12 at 13:52
  • possible duplicate of [Concurrent/Non-blocking console keyboard input in Java](http://stackoverflow.com/questions/2249680/concurrent-non-blocking-console-keyboard-input-in-java) – jtahlborn Apr 14 '12 at 13:54

1 Answers1

1

Your options are:

  • Create a GUI window. You can can receive asynchronous key events from an awt/swing window via key event listener.

    See code sample in last answer here.

  • Create separate thread in your program to wait for enter key press and then signal the main loop thread to end.

  • Use a native library like jInput or jLine (or write your own simpler equivalent using jni/jna).

    This allows you hook in to native OS's asynchronous key handling, although even then, there are often subtle dependencies on a windowing system being in place first.

Community
  • 1
  • 1
kaliatech
  • 17,579
  • 5
  • 72
  • 84