10

Most demo showing keyevent in Swing, what is the equivalent in commandline?

robert_x44
  • 8,904
  • 1
  • 30
  • 37
JohnMax
  • 219
  • 2
  • 4
  • 10

4 Answers4

10

Swing is different from a command line environment in the sense that you have no events in a console window. A standard GUI deals with objects and events. A console has no such equivalent notion.

What you do have is a standard input (as well as a standard output), which you can read from. See this question on how to read a single char from console (without waiting for a newline) - or rather, on how this isn't very easy to do in Java.

Of course, you can always do the reading asynchronously on a separate thread. i.e. the main thread will keep doing stuff, with a listener thread waiting on the I/O blocking call. But this can only be implemented and handled on the application level.

Community
  • 1
  • 1
Yuval Adam
  • 149,388
  • 85
  • 287
  • 384
6

you can use BufferedReader in a loop:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";

   while (line.equalsIgnoreCase("quit") == false) {
       line = in.readLine();

       //do something
   }

   in.close();
keyser
  • 17,711
  • 16
  • 54
  • 93
man_r
  • 61
  • 1
  • 1
5

Following code will prevent the Ctrl+C combination to stop a CLI java program.

import sun.misc.Signal; 
import sun.misc.SignalHandler;

    Signal.handle(new Signal("INT"), new SignalHandler() {
      // Signal handler method
      public void handle(Signal signal) {
        System.out.println("Got signal" + signal);
      }
    });
javauser71
  • 4,279
  • 10
  • 24
  • 29
4

KeyListener is only for swing classes.

To have an equivalent functionality in a command line app you can use the JNativeHook library which accomplishes this via JNI. This will allow you to listen for global shortcuts or mouse motion that would otherwise be impossible using pure Java. You also do not need to use Swing or other GUI classes.

Extreme Coders
  • 3,195
  • 2
  • 33
  • 49
  • The "JNativeHook library" does not help if you want to handle "Ctrl+C" key combination - the program gets terminated in the usual way. – javauser71 Aug 10 '13 at 00:31
  • Note that JnativeHook requires X11 to work (at least up to the 2.1.0 version) according to this issue: https://github.com/kwhat/jnativehook/issues/162. For example I tried to use it in a Docker container and it did not work. – dkurzaj Mar 09 '18 at 09:27