我需要每 1 秒在蓝色和红色之间更改 JLabel 颜色,我必须 SwingWorker 来完成这项工作,但我只能更改颜色一次,然后它就会停止执行任何操作。
SwingWorker 子类:
public class NewClass extends SwingWorker {
private JLabel label;
public NewClass(JLabel label) {
this.label = label;
}
@Override
protected Object doInBackground() throws Exception {
while(true) {
label.setForeground(Color.BLUE);
try {
sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
label.setForeground(Color.RED);
}
}
void changeColor() {
Color c = label.getForeground();
if(c == Color.RED)
label.setForeground(Color.BLUE);
else
label.setForeground(Color.RED);
}
}
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
NewClass g = new NewClass(label);
g.execute();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
private javax.swing.JLabel label;
}
但是如果我更改 doInBackground 以使用我的 changeColor 方法,它运行良好:
protected Object doInBackground() throws Exception {
while(true) {
changeColor();
try {
sleep(1000);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
我不明白为什么它不能在前者中运行,我认为这两种方式是一样的。
最佳答案
它们不一样。在第一种情况下,您执行以下操作:
- 将前景色更改为蓝色
- 你等一下
- 将颜色更改为红色
- 你不会等待
- 您将颜色更改为蓝色
- 你等一下
- ...无穷无尽
关于java - JLabel setForeground 在 SwingWorker 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55258075/