0

Here is what I am trying to do:

I have a JFrame containing a JTextArea displaying updates on an on going connection. The user is supposed to be able to press the JButton to the right of it if they want to cancel the connection. However, since the connection is blocking (using) the thread while trying to connect, the GUI becomes frozen. I am looking for a quick fix. Having the ActionListener on a separate thread possibly? I do not have much experience with threads though I can make basic use of runnables.

Does the answer have something to do with using the EDT? If so how should this be implemented?

PS for clarification, the button should be able to kill a thread creating the connection. After reading it seems that an executorService. could help with this? Yes? or not at all?

4

2 回答 2

5

建议首先了解 Swing(或几乎任何 UI 框架)和多线程。这是餐巾纸版本:

  • 对 UI 的任何修改或从中读取(例如,获取文本字段的值)必须UI 线程(有时也称为“Swing 线程”或“事件调度线程”(EDT)上完成
  • 任何阻塞或长时间运行的操作(如网络通信)都不得在 UI 线程上运行。否则,它们将阻止按钮工作、更新文本等。
  • 在 Java 中,theExecutorService和它的朋友会让长时间运行或阻塞的东西在后台线程上运行变得相对容易
  • 如果后台线程发生需要您更新 UI 的事情,请将与 UI 相关的代码封装在EventQueue.invokeLater调用中。这将确保Runnable您传递的内容在 UI 线程上执行。

该类SwingWorker封装了这个逻辑,并为更简单的情况提供了一个易于使用的帮助器。

第一次这样做时,可能有点令人生畏,但彻底理解这一点是值得的,因为它不仅适用于 Swing,也适用于任何其他 UI 代码。

于 2013-04-29T11:56:23.670 回答
1

为澄清起见,该按钮应该能够终止创建连接的线程。看完好像是一个executorService。可以帮忙吗?是的?还是根本没有?

是的

  • while(localBooleanVariable)里面Runnable#Thread,普通的线程

  • 通过使用SwingWorker.cancel()

  • 最简单的可能是 SwingWorker,因为是可取消的,并且输出自publish()progress()在 EDT 上

于 2013-04-29T11:00:05.610 回答