发送键盘输出

问题描述 投票:0回答:1

我想创建一个键盘输出API类型的东西,以便为Tetris编写机器学习程序,并尝试了:

import java.awt.*;

public class Keyboard
{
    public static void main( String[] args )
    {
        Robot keyboard = new Robot();
        keyboard.keyPress(KeyEvent.VK_A);

    }

}

但是对于new Robot(),有一个错误,它显示“未处理的异常:java.awt.AWTException”。并且在此之后的一行上有一个错误:“无法解析符号'KeyEvent'”,即使我有import java.awt.*;。我在做什么错?

java exception import awt
1个回答
-2
投票
 //Don't use static (*) import just import what you need in this case

import java.awt.Robot;
import java.awt.event.KeyEvent;

public class MainClass {

   public static void main(String[] args) {

    try {
        Robot rob = new Robot();
        // Robot can throw an AWTException
        // we need surround him with try-catch block
        // Or declare exception throw in current method

        // Pressing button
        rob.keyPress(KeyEvent.VK_A);

        // Releasing button in case if we don't do that key may stay in press state
        rob.keyRelease(KeyEvent.VK_A);
    } catch (Exception e) {
        // Process exception if something go wrong
        e.printStackTrace();
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.