KeyBindings in JavaFX 2

喜欢而已 提交于 2019-12-23 19:55:42

问题


How to use KeyBindings in JFX 2? I need to reassign Enter key from carrige returning to my own function, and for carrige returning assign CTRL+ENTER

I've tried this way, but still it makes a new line.

messageArea.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent keyEvent) {
            if (keyEvent.getCode() == KeyCode.ENTER) {
                sendMessage();
            }
        }
    });

回答1:


If want to prevent the default behavior of event you are filtering, you need to consume it.

There are numerous kinds of KeyEvents, you may want to filter on KeyEvent.ANY instead of just KeyEvent.KEY_PRESSED and consume them all.




回答2:


As an addition to jewelsea's answer. To control key combinations use:

if (event.getCode().equals(KeyCode.ENTER) && event.isControlDown()) { // CTRL + ENTER
    messageArea.setText(messageArea.getText() + "\n");
}

in your handler.



来源:https://stackoverflow.com/questions/10440099/keybindings-in-javafx-2

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