简体   繁体   中英

Loop method without freezing the GUI?

I am currently working on a small program that collects a list of match-ups from a website which I feed into a jList for my GUI.

I wanted to loop a method that refreshes the Elements of the List so that a match-up doesn't show up in the list once it is finished. For this I need to have the loop running all the time but this leads to the GUI freezing.

I tried to find a way around it and read something about a Timer which didn't quite work for me and creating a new Thread but this didn't work with my list as it got out of bounds after the first loop.

I checked that it has nothing to do with the method that I call so the method that needs to be looped isn't the problem.

Does anyone have an idea how I can loop a method without freezing the whole GUI. Something like this

while (true) {
   dlm.removeAllElements(); //To remove all elements from the List
   getMatches(); //Adds the matches to dlm whic
    sleep(6000); //wait 6 seconds to refresh
}

This is the code which I used to test a loop that doesn't crash.

new Thread(new Runnable() {
   public void run() {
      while (true) {
         dlm.removeAllElements(); //To remove all elements from the List
         getMatches(); //Adds the matches to dlm whic
         sleep(6000); //wait 6 seconds to refresh
      } 
    };
 }).start();

First have a look at Concurrency in Swing , in particular the section in Worker Threads .

Based on the limited code, I'd also recommend having a look at How to use Swing Timers

Remember, Swing is NOT thread safe and IS single threaded. This means (as you've discovered) that you should not perform long running or blocking operations within the context of the Event Dispatching Thread AND you should not update the UI from outside the context of the Event Dispatching Thread.

Both solutions ( SwingWorker and Swing Timer ) provide means to allow you to wait for some period of time before updating the UI, which you use will ultimately depend on your overall problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM