views:

199

answers:

3

I have the following bit of code in a method called by clicking the send button, or pressing enter in the message text field in a piece of code.

// 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 blanks the text area. However, after a message is sent by pressing the enter button, rather than being empty, the text box contains a newline.

My guess is that after my event handler runs, THEN the newline character is being added. How to I stop the newline being added?

+10  A: 

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();
 }
}
akf
A: 

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.

camickr
Being new to the forum as I understand it, the -2 indicates a couple of people believe the answer is wrong or missleading. Did I get the negative because I didn't explain what an Action is or for some other reason?Also, should I be receiving automatic emails whenever a new solution/comment is added to the posting?
camickr
A: 

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

Santhosh Kumar T