This is kind of what I'm trying to do. I'd like to do something, have a mini 1 second wait then do something else. The below example illustrates...

    private void someTypeOfMouseClicked(java.awt.event.MouseEvent evt) {                                 
        handleMouseClick(j);
    }                                

    private void handleMouseClick(JLabel j) {
    j.setText("hi");
    Thread.sleep(1000);
    j.setText("yo");
    }

What happens is that it takes 1 second then "hi" and "yo" are set together. Whereas the code clearly indicates there should be a delay between the two events.

Recommended Answers

All 3 Replies

use Swing Timer instead of Thread.sleep(int),

Everything to do with Swing (eg painting the screen, running actionPerformed methods) happens on a single thread - the "Event Dispatch Thread", or "EDT", or "Swing thread".
That means that once your mouse click method starts NOTHING else will happen in Swing, including no screen updates, until your method finishes. You can update stuff and loop and sleep as much as you like, but none of that will affect what's on the screen until your method has terminated.

If you want to do stuff in steps over a period of time, here is the right way:
In your mouse handler start a javax.swing.Timer, and return. When the timer fires you can update whatever needs updating and return.

That worked guys. I would've appreciated a more practical example but was able to work it out in this case. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.