Stopping default event behavior in Swing

I have the next bit of code in a method called by clicking a submit button, or by pressing enter in a message text box in a code snippet.

// In class ChatWindow
private void messageTextAreaKeyPressed(java.awt.event.KeyEvent evt) { // Event handler created by Netbeans GUI designer to call this method.           
    if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
        sendMessage();
    }
}   
public void sendMessage() {
    String currentMessage = messageTextArea.getText();
    addMessage("You", currentMessage);
    app.sendMessage(currentMessage, 1);
    messageTextArea.setText("");
}

The last bit of code closes the text area. However, after sending a message by pressing the enter button, and not empty, the text field contains a new line.

I assume that after starting the event handler, THEN adds a newline. How to stop adding a new line?

+5
source share
3 answers

try adding evt.consume()after your call onsendMessage()

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

Action Enter JTextArea , . , Action Action. , Action JButton ( JMenuItem ..). Action ActionListener, , , actionPerformed().

, , . Swing .

+9

,   , ;

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 interested, I applied the Autoindent function to textarea using this technique: here

+2
source

All Articles