Most demo showing keyevent in Swing, what is the equivalent in commandline?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
you can use
BufferedReader
in a loop: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 useSwing
or other GUI classes.Following code will prevent the Ctrl+C combination to stop a CLI java program.
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.