Stopping default behavior of events in Swing(在 Swing 中停止事件的默认行为)
问题描述
我在通过单击发送按钮或在一段代码的消息文本字段中按 Enter 调用的方法中有以下代码.
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?
推荐答案
尝试在调用 sendMessage()
private void messageTextAreaKeyPressed(java.awt.event.KeyEvent evt) {
if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
sendMessage();
evt.consume();
}
}
这篇关于在 Swing 中停止事件的默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Swing 中停止事件的默认行为
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01