问题
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