Robin
Robin

Reputation: 5486

Java robot not working

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?

Upvotes: 1

Views: 4313

Answers (2)

Mayur
Mayur

Reputation: 124

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.

Upvotes: 2

Mordechai
Mordechai

Reputation: 16302

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.

Upvotes: 1

Related Questions