[英]Java System.in.read() vs Event Handler?
Assuming I have something like this: 假设我有这样的事情:
x= (char) System.in.read();
if(x == 'a') {
// Do something;
}
How much different is it from something like: 它与以下内容有何不同:
public void handle(KeyEvent event) {
switch (event.getCode()) {
case A: // Do something;
case ENTER: // Do something else;
}
}
I mean when should I use the first and when the second? 我的意思是什么时候应该使用第一个,什么时候应该使用第二个? What are the pros and cons?
优缺点都有什么?
The two approaches are getting input from the user in two different ways. 两种方法都以两种不同的方式从用户那里获取输入。
The first is reading characters from the JVM's "standard input" stream. 首先是从JVM的“标准输入”流中读取字符。 If you ran your application without redirecting standard input, this stream is likely to be coming from the "console window" where you launched the JVM.
如果您在不重定向标准输入的情况下运行应用程序,则此流很可能来自启动JVM的“控制台窗口”。 The keystrokes on the console window are processed by the console / OS line editor until the user types ENTER.
控制台/ OS行编辑器将处理控制台窗口上的击键,直到用户键入ENTER。 When that happens a line of characters is delivered to the input stream ready to be read by the JVM / Java application.
发生这种情况时,会将一行字符传递到输入流,以供JVM / Java应用程序读取。
The second is processing keyboard events directly. 第二个是直接处理键盘事件。 However, this only works in a GUI application.
但是,这仅在GUI应用程序中有效。 It only sees the keyboard events directed at the application's window(s).
它只会看到直接指向应用程序窗口的键盘事件。
I mean when should I use the first and when the second?
我的意思是什么时候应该使用第一个,什么时候应该使用第二个?
Use the first in a console-based where you don't need to see characters at the instance the user presses a key. 在基于控制台的控制台中使用第一个,您无需在用户按下键的实例上看到字符。
Use the second when you have a GUI based application and you want to get input from the user interactively. 当您具有基于GUI的应用程序并且想要以交互方式从用户那里获取输入时,请使用第二个。
What are the pros and cons?
优缺点都有什么?
That is self-evident from the above. 从上面看,这是不言而喻的。 However, there are a couple additional "cons".
但是,还有几个其他的“缺点”。
With the System.in approach: 使用System.in方法:
System.in
stream could be coming from a file. System.in
流可能来自文件。 If you need to be sure (or as sure as possible) that you are talking to a real user, use System.console()
... and check that you don't get null
. System.console()
...并检查您没有得到null
。 With the EventHandler
approach: 使用
EventHandler
方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.