setIcon on JButton then Thread.sleep then setIcon to null but it not work

I want to do step like this.

When click on JButton, set Icon to such JButton,

then delay for awhile says, 1 second.

Then remove Icon from JButton.

My demo code is below, but when I did it,

JButton doesn't show icon at all.

It goes like after click, program pauses, then nothing shows on JButton

What else can I do to do this?

Thank you very much..

=========== domo code ============

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

public class Demo extends JFrame implements ActionListener {

ImageIcon icon = new ImageIcon("sprites/0.png");

JButton b = new JButton("Click");

Demo(){

b.addActionListener(this);

add(b);

this.setSize(200,200);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setVisible(true);

}

public void actionPerformed(ActionEvent e) {

b.setIcon(icon);

try {Thread.sleep(1000);} catch (InterruptedException e1) {}

b.setIcon(null);

}

public static void main(String[] args) {

new Demo();

}

}

[1158 byte] By [rikpa] at [2007-10-3 2:53:39]
# 1

When you join a forum you should learn how to use it correctly before posting a question.

1) Swing related questions should be posted in the Swing forum.

2) Use the "Code" formatting tags when posting code so the code is readable.

3) Use the "Preview" button to see if you question is readable before posting the question.

> It goes like after click, program pauses, then nothing shows on JButton

Thats because you Thread.sleep(...) method is causing the GUI Event Thread to sleep, which means it can't paint your new icon. When it wakes up it paints the null icon.

You need to use a separate Thread to sleep before updating the icon. Read the Swiing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html]How to Use Threads[/url].

Or, even better use a Swing Timer to schedule the resetting of the icon. The "How to Use Timers" tutorial is below the threads tutorial.

camickra at 2007-7-14 20:42:42 > top of Java-index,Java Essentials,Java Programming...
# 2
Thank you for the reply.I checked 2 classed. swing.Timer and SwingUtilities.It works as you suggested.Also, sorry for posting in wrong topic -_-"and not using code tag.I won't do it wrong next time :)Thank you again
rikpa at 2007-7-14 20:42:42 > top of Java-index,Java Essentials,Java Programming...