0

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");
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

2

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

0x6C38
  • 6,796
  • 4
  • 35
  • 47
  • 2
    Swing Timer is certainly the way to go for the original problem. 1+ – Hovercraft Full Of Eels May 11 '13 at 14:37
  • Thanks for the answers! Would SwingTimer or SwingWorker work? As I am new to these, can you please provide some code for my example for me to study it? :) Thank you –  May 11 '13 at 14:45
  • 3
    @darkchampionz Follow the tutorials, it's easy. Try it by yourself and if you didn't success post it here and we'll help you! – Maroun May 11 '13 at 14:47
  • Ok! Can you provide me a link!? :D –  May 11 '13 at 14:57
  • 1
    I suggest you read the [documentation](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) first and then maybe check out [this tutorial](http://www.java2s.com/Tutorial/Java/0240__Swing/SwingTimers.htm) and [this question](http://stackoverflow.com/questions/13503788/confusion-with-the-java-swing-timer). – 0x6C38 May 11 '13 at 15:08
1

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.

christopher
  • 26,815
  • 5
  • 55
  • 89