执行被困在按钮内

时间:2011-05-18 14:02:29

标签: java swing button execution

我有一个在按钮内部调用的方法,它几乎运行无限循环。运行此方法时,我无法访问其他按钮。

运行此方法时如何释放界面以访问其他按钮?

//methods inside the button
this.setCrawlingParameters();
webcrawler = MasterCrawler.getInstance();
webcrawler.resumeCrawling(); //<-- the infinite loop method

2 个答案:

答案 0 :(得分:7)

您需要使用SwingWorker

Swing的工作方式是它有一个主线程,即管理UI的事件调度线程(EDT)。在Swing文档中,您将看到建议永远不要在EDT中长时间运行任务,因为,由于它管理UI,如果您做一些计算量大的操作,UI将会冻结。这正是你在做的事情。

所以你需要让你的按钮调用一个SwingWorker,这样才能在另一个线程中完成。注意不要从SwingWorker修改UI元素;所有UI代码都需要在EDT中执行。

如果单击SwingWorker的链接,您将看到:

  

不应该运行耗时的任务   在事件派遣线程上。   否则应用程序变为   反应迟钝。 Swing组件应该   可在事件派遣中访问   仅限线程

以及有关如何使用SwingWorker的示例的链接。

答案 1 :(得分:3)

开始一个新主题:

// In your button:
Runnable runner = new Runnable()
{
    public void run()
    {
         setCrawlingParameters(); // I removed the "this", you can replace with a qualified this
         webcrawler = MasterCrawler.getInstance();
         webcrawler.resumeCrawling(); //<-- the infinite loop method
    }
}
new Thread(runner, "A name for your thread").start();