如何在按下Enter键时停止光标移动到TextArea中的新行 [英] How to stop cursor from moving to a new line in a TextArea when Enter is pressed
问题描述
我有一个聊天应用程序.我希望chatTextArea
中的光标返回到TextArea chatTextArea
的位置0.
I have a Chat application. I'd like the cursor in the chatTextArea
to get back to the position 0 of the TextArea chatTextArea
.
但是,这是行不通的:
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.
推荐答案
TextArea
内部不使用onKeyPressed
属性来处理键盘输入.因此,设置onKeyPressed
不会删除原始事件处理程序.
The TextArea
internally does not use the onKeyPressed
property to handle keyboard input. Therefore, setting onKeyPressed
does not remove the original event handler.
要防止TextArea
的Enter键内部处理程序,您需要添加一个使用事件的事件过滤器:
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
}
}
});
事件 filter 使用相同的EventHandler
接口.区别仅在于它在任何事件 handler 之前被调用.如果事件过滤器使用事件,则不会为该事件触发任何事件处理程序.
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.
这篇关于如何在按下Enter键时停止光标移动到TextArea中的新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!