How to stop cursor from moving to a new line in a TextArea when Enter is pressed

可紊 提交于 2020-01-16 00:39:24

问题


I have a Chat application. I'd like the cursor in the chatTextArea to get back to the position 0 of the TextArea chatTextArea.

This, however, won't work:

chatTextArea.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if (ke.getCode().equals(KeyCode.ENTER)) {
            ChatClient.main(new String[]{"localhost", String.valueOf(4444), chatTextArea.getText()});
            chatTextArea.setText("");
            chatTextArea.positionCaret(0);
        }
    }
});

How can I get it to work? Thank you.


回答1:


The TextArea internally does not use the onKeyPressed property to handle keyboard input. Therefore, setting onKeyPressed does not remove the original event handler.

To prevent TextArea's internal handler for the Enter key, you need to add an event filter that consumes the event:

chatTextArea.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if (ke.getCode().equals(KeyCode.ENTER)) {
            ChatClient.main(new String[]{"localhost", String.valueOf(4444), chatTextArea.getText()});
            chatTextArea.setText("");
            // chatTextArea.positionCaret(0); // not necessary
            ke.consume(); // necessary to prevent event handlers for this event
        }
    }
});

Event filter uses the same EventHandler interface. The difference is only that it is called before any event handler. If an event filter consumes the event, no event handlers are fired for that event.



来源:https://stackoverflow.com/questions/26752924/how-to-stop-cursor-from-moving-to-a-new-line-in-a-textarea-when-enter-is-pressed

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