Issue
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.
Solution
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.
Answered By - Tomas Mikula
Answer Checked By - Pedro (JavaFixing Volunteer)