Java:从控制台读取密钥而不按回车键

时间:2015-06-01 01:35:37

标签: java input console readkey

我想在用户按特定键时中断程序。 我尝试下面的代码,但它只能使用回车键。

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)

0 个答案:

没有答案