且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JButton ActionListener - GUI 仅在单击 JButton 后更新

更新时间:2023-12-02 11:35:46

不要在 EDT,否则 GUI 将无响应,您可能看不到 GUI 更新.您可以使用的***选择是 SwingWorker代码>:

Do not perform any intensive operations within EDT, otherwise the GUI will be unresponsive and you might not see the GUI updates. Best choice you can use is SwingWorker:

  • 覆盖doInBackground(),并将任何长操作放入此方法中,以便它在单独的线程上运行,而不是在 EDT.

对于 doInBackground(),使用publish(V... chunks) 将数据发送到process(列出块).您需要覆盖 process(List chunks).另请注意 process(List chunks)EDT.

doInBackground() 返回,done()EDT 并且您可以覆盖它以将其用于任何 GUI 更新.您还可以检索从 doInBackground() 使用 get().

After doInBackground() returns, done() executes on EDT and you can override it to use it for any GUI updates. You can also retrieve the value returned from doInBackground() by using get().

注意SwingWorker<T,V>通用,并且您需要指定类型.T 是从 doInBackground()get(),而 V 是你传递给的元素类型process(List chunks) 通过 publish(V...块).

Note that SwingWorker<T,V> is generic, and you need to specify the types. T is the type of object returned from doInBackground() and get(), while V is the type of elements you passed to process(List<V> chunks) via publish(V... chunks).

execute() 方法通过调用 doInBackground() 首先.

有关这方面的更多信息,请阅读Swing 中的并发.

For more on this, please read Concurrency in Swing.