Search code examples
javamultithreadingswingsleep

java - JLabel setForeground doesn't work in SwingWorker


I need to change a JLabel color between blue and red every 1 second, i have to SwingWorker to do this job but i can only change the color once and then it stops doing anything.

SwingWorker subclass:

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;

}

But if i change the doInBackground to use my changeColor method, it runs well:

protected Object doInBackground() throws Exception {
        while(true) {
            changeColor();
            try {
                sleep(1000);
            } catch (Exception ex) {
                 ex.printStackTrace();
            }  
        }
}

I can't figure out why it doesn't run in the former, i thought these 2 ways are just the same.


Solution

  • They are not the same. In the first case you do the following:

    • you change the foreground color to blue
    • you wait one second
    • you change the color to red
    • you do not wait
    • you change to color to blue
    • you wait one second
    • ... ad infinitum