How to cast a keyboard event

2019-09-12 09:14发布

问题:

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.