How to cast a keyboard event

和自甴很熟 提交于 2019-12-11 23:31:26

问题


Where it says **spacebarpressed**, I want to cast an event:

public static void main(String[] args) throws IOException, AWTException{

    final Robot robot = new Robot();

    robot.delay(2000);

    while(true)
    {
        if( **spacebarpressed** ) {
            robot.mousePress(InputEvent.BUTTON1_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_MASK);

            robot.delay(50);
        }
        else {
            robot.delay(50);
        }
    }
}

回答1:


You want to check if spacebar is pressed? If that's so, you need an inner private class that implements KeyListener, but you need to hook it up to a JFrame however... I don't know about any other way.

private class Key
    implements KeyListener
{
    private boolean spacebarPressed = false;

    @Override
    public void keyTyped(KeyEvent e)
    {
    }

    @Override
    public void keyPressed(KeyEvent e)
    {
        if(e.getKeyCode() == KeyEvent.VK_SPACE)
        {
            spacebarPressed = true;
        }
    }

    @Override
    public void keyReleased(KeyEvent e)
    {
        if(e.getKeyCode() == KeyEvent.VK_SPACE)
        {
            spacebarPressed = false;
        }
    }

    public boolean isSpacebarPressed()
    {
        return spacebarPressed;
    }
}

And then just call isSpacebarPressed() in your while loop to check.



来源:https://stackoverflow.com/questions/18705664/how-to-cast-a-keyboard-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!