如何在按下Enter键时停止光标移动到TextArea中的新行 [英] How to stop cursor from moving to a new line in a TextArea when Enter is pressed

查看:89
本文介绍了如何在按下Enter键时停止光标移动到TextArea中的新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个聊天应用程序.我希望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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆