Simple key listener - 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.开发者_如何学运维
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.
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.
精彩评论