Stopping default behavior of events in Swing

心不动则不痛 提交于 2019-12-01 17:55:11

try adding evt.consume() after your call to sendMessage()

private void messageTextAreaKeyPressed(java.awt.event.KeyEvent evt) { 
 if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
    sendMessage();
    evt.consume();
 }
}  
camickr

The default Action for the Enter key in a JTextArea is to insert a new line as you have seen. So the solution is to replace the default Action with a custom Action. The benefit of this approach is that this Action can also be used by the JButton (or JMenuItem etc.). An Action is basically the same as an ActionListener, all you need to do is implement the actionPerformed() method.

Read up on Key Bindings to see how this is done. All Swing components use Key Bindings.

as camickr said, you should bind action to enter key;

Action sendAction = new AbstractAction("Send"){
    public void actionPerformed(ActionEvent ae){
       // do your stuff here
    }
};

textarea.registerKeyboardAction(sendAction, 
       KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
sendButton.setAction(sendAction);

if you are more interesed, I implemented Autoindent feature for textarea, using this technique: here

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