[英]java - JLabel setForeground doesn't work in SwingWorker
我需要每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();
}
}
}
我不知道為什么它不能在前者中運行,我認為這兩種方式是相同的。
她們不一樣。 在第一種情況下,請執行以下操作:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.