简单的按键监听器 - java
我有一段处于无限循环内的代码。我想实现一种方法来检查我是否按下按钮作为循环断路器。
while(true)
{
...
if(this.escapeKeyIsPressed()) //Should return true if escape is pressed at that milisecond
{
...
break;
}
}
在java中做到这一点最简单的方法是什么?我应该查看哪个图书馆?
预先感谢您的宝贵时间。
I have a piece of code that is within an infinite loop. I would like to implement a method which checks whether I press a button or not as a loop breaker.
while(true)
{
...
if(this.escapeKeyIsPressed()) //Should return true if escape is pressed at that milisecond
{
...
break;
}
}
What is the easiest way to do this in java ? Which library should I look into ?
Thanks in advance for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此页面介绍了设置控制台进入非阻塞模式以读取字符,您可以使用它来中断循环。它还提供了一些适用于 Python 和 Java 的其他方法,但它必须被认为有些 hacky 和不可移植(例如在 Windows 下无法工作)。恐怕我不认为有一种“好的”简单方法可以做到这一点。
This page presents a method of setting the console into non-blocking mode in order to read a character, which you could use to break your loop. It also presents a few other methods for both Python and Java, but it has to be considered somewhat hacky and non-portable (wouldn't work under Windows for example). I don't think there is a 'nice' easy way to do it I'm afraid.
不幸的是, KeyListener 接口由“java.awt.event”包提供,该包是Java 图形和窗口工具包的一部分,这意味着该类只能由窗口应用程序(例如Swing 程序和Applet)使用。
第三方解决方案可能存在,但核心 Java 并没有提供可靠的方法来完成您的要求。
Unfortunately, the KeyListener interface is provided by the "java.awt.event" package which is part of Java's graphics and windowing toolkit, which means that this class is only usable by windowed applications (e.g. Swing programs and Applets).
Third party solutions may exist but core Java does not provide a reliable way to do what your'e asking for.