在 JButton 操作上多次替换 JLabel 文本
Replace JLabel text multiple times on JButton action
单击 JButton
时,我需要使用 setText
清空 JLabel
。在 actionPerformed
内,我有另一个 Java class 电话。
如果 returns 异常,那么我必须将标签更改为 setText("Error occurred")
。
如果是 returns 结果,我必须将相同的标签更改为 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 分离了线程,并且能够实现我的要求。
这 link 让我理解了 Swing 的工作原理。 https://www.geeksforgeeks.org/swingworker-in-java/
单击 JButton
时,我需要使用 setText
清空 JLabel
。在 actionPerformed
内,我有另一个 Java class 电话。
如果 returns 异常,那么我必须将标签更改为 setText("Error occurred")
。
如果是 returns 结果,我必须将相同的标签更改为 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 分离了线程,并且能够实现我的要求。
这 link 让我理解了 Swing 的工作原理。 https://www.geeksforgeeks.org/swingworker-in-java/