Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically simulate arrow key presses in Java FX

I want to make my JFX application simulate arrow key presses (when they are registered in a TextField), but I can't figure out how to send anything other than Strings or bytes.

I'm imagining something like this:

static EventHandler<KeyEvent> KEY() {
    E = new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent ke) {
            if (ke.getCode().equals(KeyCode.UP)) {
                try {
                    //someObject.SimulateKeyPress(KeyCode.UP);

                    //OR

                    //coolObject.SendKey((char)KEY_UPKEY));
                } catch (Exception ex) {
                    //Teleport goats
                }
            }
        }
    };

    return E;
}
like image 756
Adam Jensen Avatar asked Jun 17 '14 08:06

Adam Jensen


2 Answers

Use the class Robot

 try {
    Robot r = new Robot();
    //there are other methods such as positioning mouse and mouseclicks etc.
    r.keyPress(java.awt.event.KeyEvent.VK_UP);
    r.keyRelease(java.awt.event.KeyEvent.VK_UP);
 } catch (AWTException e) {
    //Teleport penguins  
 }
like image 172
Cobbles Avatar answered Oct 14 '22 08:10

Cobbles


You cannot instantiate the type Robot. You should rather do :

  Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot();
like image 27
Lion_CH Avatar answered Oct 14 '22 10:10

Lion_CH