1

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?

3
  • What exactly is not working? syntax or runtime? Commented Mar 8, 2015 at 20:30
  • @MouseEvent When I say, 'scroll up', in the console it does display 'scroll up', but nothing happens, I mean it does not press the Up button. Commented Mar 8, 2015 at 20:33
  • 2
    The Kelsey events will be sent to the currently focused compnents. Also make sure you call keyRelease as well Commented Mar 8, 2015 at 20:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.