anna
anna

Reputation: 755

Sleep method locks my GUI

What I want to do is to make some part of the code in a class of my programm to wait for sometime, but my problem is that the way I am trying to it makes my GUI to stuck. I mean, pressing a button i make my program to wait for sometime, while my program is waiting i press a button, the button is pressed but after that if i try to press any other button while the program is still waiting i can't, the first button i pressed seems to be pressed and the other button can't be pressed although the program does what I want to do(accepts all the commands) the only problem is that my GUI is locked.

Upvotes: 0

Views: 852

Answers (4)

Jimmy D
Jimmy D

Reputation: 5376

Your GUI is loaded and runs on one thread, your wait function runs on the same thread, thereby locking up the GUI. You need to start the wait function on a separate thread.

Upvotes: -1

Paul
Paul

Reputation: 20091

You didn't provide any code so it's impossible to give direct input on your code. If you're using Swing and need to perform time-consuming processing, use a Swing Worker thread. Here is a tutorial on using the SwingWorker class:

Using a Swing Worker Thread

Upvotes: 0

evanwong
evanwong

Reputation: 5134

For the parts you are doing sleep and after when the first button pressed, you can try this:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
        //and whatever you need to do
    }
});

If you need to use any local variables in the button pressed method, they need to be the final variables.

Upvotes: 1

ziesemer
ziesemer

Reputation: 28707

You need to use multiple threads. Any "work" that needs to be done that may take any significant / noticeable amount of time needs to be done in its own thread. (This certainly includes any code where you are calling sleep.)

Here are 3 good references:

Upvotes: 4

Related Questions