user2276872
user2276872

Reputation:

Thread sleep in actionPerformed

I am trying to make a tiny program that has 3 buttons, all of them of white color. Pressing the first button (that has the text "Go!") will cause the second button to become orange for 3 seconds and then, after that time, it will become white again AND the third button will become permanently green.

However, in my following code, I have a problem achieving this: When hitting the button "Go!", it causes my program to somewhat freeze for 3 seconds and then the third button becomes green. Can you please help me?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Example extends JFrame
{
public Example(String title)
{
    super(title);
    GridLayout gl = new GridLayout(3,1);
    setLayout(gl);

    final JButton b1 = new JButton("Go!");
    final JButton b2 = new JButton();
    final JButton b3 = new JButton();

    b1.setBackground(Color.WHITE);
    b2.setBackground(Color.WHITE);
    b3.setBackground(Color.WHITE);

    b1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            b2.setBackground(Color.ORANGE);
            try
            {
                Thread.sleep(3000);
            } catch (InterruptedException ie) {}
            b2.setBackground(Color.WHITE);
            b3.setBackground(Color.GREEN);
        }
    });                

    add(b1);
    add(b2);
    add(b3);

    setSize(50,200);
    setVisible(true);
}

public static void main(String[] args)
{
    Example ex = new Example("My Example");
}
}

Upvotes: 0

Views: 1977

Answers (2)

0x6C38
0x6C38

Reputation: 7076

Swing is single threaded. Calling Thread.sleep in the EDT prevents UI updates. Use a Swing Timer instead.

Upvotes: 2

christopher
christopher

Reputation: 27346

You're calling Thread.sleep(3000) on the main thread. Hence why your program freezes for three seconds. As @MarounMaroun suggested, you should use a SwingWorker. Here is the documentation.

Upvotes: 1

Related Questions