简体   繁体   English

如何进行键盘事件

[英]How to cast a keyboard event

Where it says **spacebarpressed** , I want to cast an event: 它说**spacebarpressed** ,我想投射一个事件:

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);
        }
    }
}

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. 如果是这样的话,您需要一个内部私有类来实现KeyListener ,但是您需要将其连接到JFrame ……我不知道其他任何方式。

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. 然后只需在while循环中调用isSpacebarPressed()即可进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM