Java robot not working

戏子无情 提交于 2021-02-05 08:28:30

问题


I am working on a simple speech recognition project. I have a command called scroll up where I want to use the class to press the UP key.

This is the code:

        else if(resultText.equalsIgnoreCase("scroll up"))
        {
            try {
                Robot robot = new Robot();
                robot.delay(5000);
                robot.keyPress(KeyEvent.VK_UP);
                robot.delay(1000);
                robot.keyPress(KeyEvent.VK_UP);
                robot.delay(1000);
                robot.keyPress(KeyEvent.VK_UP);
            }
            catch (AWTException e){
                e.printStackTrace();
            }
        }

I have already imported these

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

Now the same code works well in another project, but not in the present project. What am I doing wrong?


回答1:


Try this:

else if (resultText.equalsIgnoreCase("scroll up")) {
    try {
        Robot robot = new Robot();
        robot.delay(5000);
        robot.keyPress(KeyEvent.VK_UP);

        robot.delay(1000);
        robot.keyRelease(KeyEvent.VK_UP);
        robot.keyPress(KeyEvent.VK_UP);
        robot.delay(1000);
        robot.keyRelease(KeyEvent.VK_UP);
        robot.keyPress(KeyEvent.VK_UP);
        robot.delay(1000);
        robot.keyRelease(KeyEvent.VK_UP);

You have to release the same button.




回答2:


From your comment, I understood that the input comes from command-line (an anytime very important fact to include in your post). this means that the command window (or console panel - in IDE) contains the system focus, theirfore UP does nothing.

Add a requestFocus() in your code, this should help.



来源:https://stackoverflow.com/questions/28931292/java-robot-not-working

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