Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

java - Stopping default behavior of events in Swing

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...