Program-Me-Rev
Program-Me-Rev

Reputation: 6624

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

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.

Upvotes: 1

Views: 1640

Answers (1)

Tomas Mikula
Tomas Mikula

Reputation: 6537

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.

Upvotes: 4

Related Questions