简体   繁体   English

不冻结GUI的循环方法?

[英]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. 我目前正在开发一个小型程序,该程序从网站收集匹配列表,然后将其输入到GUI的jList中。

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. 为此,我需要一直运行循环,但这会导致GUI冻结。

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. 我试图找到一种解决方法,并阅读了有关Timer的一些知识,该定时器对我而言并不奏效,并创建了一个新的Thread,但这不适用于我的列表,因为它在第一次循环后就越界了。

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. 有谁知道如何在不冻结整个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 . 首先看一下Swing中的并发 ,特别是Worker Threads中的部分。

Based on the limited code, I'd also recommend having a look at How to use Swing Timers 根据有限的代码,我还建议您看看如何使用Swing计时器

Remember, Swing is NOT thread safe and IS single threaded. 请记住,Swing不是线程安全的,而是单线程的。 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. 这意味着(如您所发现的)您不应在事件调度线程的上下文中执行长时间运行或阻塞的操作,并且不应从事件调度线程的上下文外部更新UI。

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 两种解决方案( SwingWorker和Swing Timer )都提供了一些方法,使您可以等待一段时间才能更新UI,最终使用哪种方法最终取决于您的总体问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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