执行被困在按钮内
我有一个在按钮内部调用的方法,该方法几乎运行无限循环。运行此方法时我无法访问其他按钮。
在运行此方法时如何释放界面以访问其他按钮?
//methods inside the button
this.setCrawlingParameters();
webcrawler = MasterCrawler.getInstance();
webcrawler.resumeCrawling(); //<-- the infinite loop method
I have a method called inside a button that run almost an infinite loop. I can't access the other buttons while running this method.
How I make to free the interface to access other buttons while running this method?
//methods inside the button
this.setCrawlingParameters();
webcrawler = MasterCrawler.getInstance();
webcrawler.resumeCrawling(); //<-- the infinite loop method
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要使用一个 SwingWorker
的方式Swing 的工作原理是它有一个主线程,即管理 UI 的事件调度线程 (EDT)。在 Swing 文档中,您将看到建议永远不要在 EDT 中运行长时间运行的任务,因为它管理 UI,如果您执行计算量大的操作,您的 UI 将冻结。这正是你正在做的事情。
因此,您需要让按钮调用 SwingWorker,以便在另一个线程中完成困难的工作。注意不要从 SwingWorker 修改 UI 元素;所有UI代码都需要在EDT中执行。
如果单击 SwingWorker 的链接,您将看到以下内容:
以及有关如何使用 SwingWorker 的示例的链接。
you need to use a SwingWorker
The way Swing works is that it has one main thread, the Event Dispatch Thread(EDT) that manages the UI. In the Swing documentation, you will see that it is recommended to never to long-running tasks in the EDT, because, since it manages the UI, if you do something computationally heavy your UI will freeze up. This is exactly what you are doing.
So you need to have your button invoke a SwingWorker so the hard stuff is done in another thread. Be careful not to modify UI elements from the SwingWorker; all UI code needs to be executed in the EDT.
If you click the link for SwingWorker, you will see this:
as well as links to examples on how to use a SwingWorker.
开始一个新线程:
Start a new Thread: