0

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?

Community
  • 1
  • 1
newtothissite
  • 357
  • 2
  • 6
  • 10

2 Answers2

2

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)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

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

BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • This is only going to work of component in question is actually focusable. Ps you should be using requestFocusInWindow instead of requestFocus ;) – MadProgrammer May 07 '13 at 22:16
  • @MadProgrammer All Component and JComponent-extended classes do have a `requestFocus` method, so i think it should work with every type of GUI component – BackSlash May 07 '13 at 22:22
  • I think you need to read the [docs](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#requestFocus()), *"Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow(). If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial."* – MadProgrammer May 07 '13 at 22:26