newtothissite
newtothissite

Reputation: 367

Simulate key inputs in Java for JUnit Test

I would like to simulate a Enter key press. I tried using the robot class but it doesn't seem to work:

robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
try{Thread.sleep(50);}catch(InterruptedException e){}
robot.keyRelease(KeyEvent.VK_ENTER);

In my main code, I have

 public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_ENTER) {
            System.out.println("ENTER KEY PRESSED");
            // DO SOMETHING;
        }
    }

so if the keyPress is registered, then the console should print out "ENTER KEY PRESSED", but it's not doing that.

Thanks for your help!

Also if you know a way to simulate key events without robot class, please post below :).

Source: How to simulate keyboard presses in java?

Upvotes: 0

Views: 3704

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

The problem isn't just with how you are using Robot.

KeyListener will only respond when the component it is attached to is focusable and has focus.

First, don't use KeyListener, use key bindings instead, this will help over come the focus issues.

Second, make sure that the window you are trying to interact with actually keyboard focus (and the focus isn't on control that will consume the Enter key)

Upvotes: 2

BackSlash
BackSlash

Reputation: 22233

I assume that you have previously added the KeyListener to your component. If not, please use this:

yourComponent.addKeyListener(yourKeyListener);

If you already did that and it still doesn't work, probably you didn't request focus for the component to which you added the KeyListener

Try adding this before the robot.keyPress:

yourComponent.requestFocus();

Where yourComponent is the component which should generate the KeyPressed event

Upvotes: 0

Related Questions