Java key listener in Commandline

2019-01-06 20:00发布

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

4条回答
相关推荐>>
2楼-- · 2019-01-06 20:40

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();
查看更多
3楼-- · 2019-01-06 20:40

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.

查看更多
相关推荐>>
4楼-- · 2019-01-06 20:48

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);
      }
    });
查看更多
小情绪 Triste *
5楼-- · 2019-01-06 20:50

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.

查看更多
登录 后发表回答