GreatPanda3
GreatPanda3

Reputation: 21

'keyPress()' method for Robot object isn't typing anything

I'm trying to code a program in Java that automatically types each character in a string using the Robot class. I've used it to make a similar automated program a while ago (which I'll refer to as the 'previous project') that used 'keyPress()'. This and most, if not all, of the other methods for the Robot class which I needed to use worked perfectly.

Now I've started and 'keyPress()' isn't typing anything, regardless of the KeyEvent I pass as an argument. I thought I had written the code incorrectly, so I ran my previous project just to make sure it worked, but it didn't.

Here's the snippet of code I used for the previous project and my current one (which you can also use to test this).

EDIT: Try the on a text editor or anything that functions like a text field. I've now shown the entire demo class.

// demo procedure
public class DemoClass() {
    public static void main(String[] args) {
        new DemoClass().run()
    }

    public void run() {
        try {
            Robot robot = new Robot();
            
            for (int i = 1; i <= 30; i++) {
                robot.keyPress(KeyEvent.VK_A);
                robot.delay(100);

                System.out.println("Typed key");
            }

        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}

'Typed key' gets printed 30 times and no errors appear in the output either.

I've tried;

None of these have produced results. I've checked the code from multiple sources (articles and videos), all of which have the same code stub. I've read that some software prevent Robot objects from typing/clicking in them, but both typing and clicking worked when I was developing my previous project.

Upvotes: 1

Views: 207

Answers (1)

GreatPanda3
GreatPanda3

Reputation: 21

So I woke up today and... the program works.

I still don't know why it wasn't working in the first place or how the problem fixed itself (magic?). Running the sudo command didn't seem to make a difference, and none of the software I'm dealing with prevent a Robot object from automated typing/clicking.

It's most likely just a me-problem since other people managed to get it working. Since it's happened once it'll probably happen again.

Anyways, thanks to everyone that helped! If future readers have any ideas of why it didn't work then feel free to share them.

Upvotes: 1

Related Questions