如何解决在 JButton 操作上多次替换 JLabel 文本
当点击 JButton
时,我需要使用 JLabel
清空 setText
。在 actionPerformed
中,我有另一个 Java 类调用。
如果它返回异常,那么我必须将标签更改为 setText("Error occurred")
。
如果它返回结果,我必须将相同的标签更改为 setText("Process completed")
。
我试图生成一个异常并且它工作正常,但是当我再次单击该按钮时,文本不会被替换为空字符串。相反,它仍然显示“发生错误”。
请查看下面的代码,让我知道我需要更改什么。
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label1.setText("");
if(lblSource.getText().isEmpty()) {
label2.setText("You have missed to select!! Please select it");
}
else {
label1.setText("processing... ");
VelConverter v = new VelConverter(locations);
String response = v.convert();
if(response.startsWith("Exception")) {
//code
label1.setText("Error Occurred");
}
else {
//code
label1.setText("Completed");
}
}
}
解决方法
感谢 Rocco 和 Andrew Thomson。您对并发的建议使我对 Swing worker 进行了研究。我只是使用 Swing worker 分离线程,我能够实现我的要求。
这个链接让我明白了 Swing 的工作原理。 https://www.geeksforgeeks.org/swingworker-in-java/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。