How to programmatically simulate arrow key presses in Java FX

∥☆過路亽.° 提交于 2020-01-03 09:57:12

问题


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;
}

回答1:


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  
 }



回答2:


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

  Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot();


来源:https://stackoverflow.com/questions/24258995/how-to-programmatically-simulate-arrow-key-presses-in-java-fx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!