我想在用户按特定键时中断程序。 我尝试下面的代码,但它只能使用回车键。
java.io.InputStreamReader reader = new java.io.InputStreamReader(System.in);
boolean b = false;
while(!b)
{
try{
if ( reader.ready())
{
// read a character and process it
System.out.println("key pressed");
b = true;
}
}
catch (java.io.IOException ioex)
{
System.out.println("IO Exception");
}
// edit, lets not hog any cpu time
try
{
Thread.sleep(50);
System.out.println("nop yet");
}
catch (InterruptedException ex)
{
// can't do much about it can we? Ignoring
System.out.println("Interrupted Exception");
}
}
C#(工作)中的等价物:
ConsoleKeyInfo k1 = new ConsoleKeyInfo('T', ConsoleKey.T, false, false, false);
ConsoleKeyInfo k = Console.ReadKey(false);
if (k== k1)
{
Environment.Exit(1);
}
修改1:
我试过线程和这个列表器,但也不行。
public void keyTyped(KeyEvent e)
public void keyPressed(KeyEvent e)
public void keyReleased(KeyEvent e)