tags:

views:

88

answers:

4

I have a piece of code in Java which draws 2 icons to the screen. I want to enforce a delay between them, and am unsure of the best way.

At the moment I have;

cell.setIcon(image1);
Thread.sleep(500); // Ignored try() for brevity
cell2.setIcon(image2);

But this seems to cause the delay before either are drawn. Why is this, and how can I fix it?

+2  A: 

Assuming you're using Swing, you need to cause the sleep to be performed on a worker thread, like so:

new SwingWorker<Void,Void>() {
    @Override
    protected Void doInBackground() throws Exception {
        Thread.sleep(500);
        return null;
    }
    @Override
    protected void done() {
        cell2.setIcon(image2);
    }
}.execute();
Devon_C_Miller
+2  A: 

Devon has the best answer for the how. As for the why, the basic problem is that the setIcon function doesn't contain the code that repaints your component. The flow looks like this:

1) You click something on the GUI
2) An event is generated, Swing calls all the listeners
3) Your code is triggered and run, setIcon is called
4) Your code finishes running and control returns to Swing
5) Swing paints any new/changed components, etc.

All of this happens on one thread. You want your delay to occur after step 3, but you don't want to block the current thread because then step 5 won't execute until after the delay. Devon's solution uses a SwingWorker to put the delay on a different thread so it won't block step 5.

Pace
A: 

I would use a Swing Timer. When you display the first Icon you start the Timer. When the Timer fires you display the second Icon.

Read the section from the Swing tutorial on How to Use Timers for more information.

camickr
A: 

Maybe this thread can help you...

Carlos Heuberger