命令行中的 Java 键侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4005574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java key listener in Commandline
提问by JohnMax
Most demo showing keyevent in Swing, what is the equivalent in commandline?
大多数演示在 Swing 中显示 keyevent,命令行中的等效项是什么?
回答by Yuval Adam
Swing is different from a command line environment in the sense that you have no eventsin a console window. A standard GUI deals with objects and events. A console has no such equivalent notion.
Swing 不同于命令行环境,因为控制台窗口中没有事件。标准 GUI 处理对象和事件。控制台没有这样的等效概念。
What you dohave is a standard input (as well as a standard output), which you can read from. See this questionon 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.
什么,你就已经是一个标准输入(以及标准输出),您可以从阅读。见这个问题上如何读取单个字符从控制台(而无需等待新行) -或者更确切地说,这是如何不是很容易用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.
当然,您始终可以在单独的线程上异步读取。即主线程将继续做事,侦听器线程等待 I/O 阻塞调用。但这只能在应用程序级别上实现和处理。
回答by man_r
you can use BufferedReader
in a loop:
您可以BufferedReader
在循环中使用:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while (line.equalsIgnoreCase("quit") == false) {
line = in.readLine();
//do something
}
in.close();
回答by Extreme Coders
KeyListener
is only for swing classes.
KeyListener
仅适用于秋千课程。
To have an equivalent functionality in a command line app you can use the JNativeHooklibrary 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.
要在命令行应用程序中具有等效功能,您可以使用JNativeHook库,它通过JNI
. 这将允许您侦听全局快捷方式或鼠标运动,否则使用纯 Java 是不可能的。您也不需要使用Swing
或其他 GUI 类。
回答by javauser71
Following code will prevent the Ctrl+C combination to stop a CLI java program.
以下代码将阻止 Ctrl+C 组合停止 CLI java 程序。
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);
}
});