且构网

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

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

更新时间:2023-12-02 11:27:40

不要在 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

对于任何GUI创建或更改 doInBackground() ,使用 publish(V ... chunk) 将数据发送到 process(List< V>组块) 。您需要覆盖 进程(列出< V>块) 。另请注意 进程(列表< V>块) EDT

For any GUI creation or changing states of GUI components within doInBackground(), use publish(V... chunks) to send data to process(List<V> chunks). You need to override process(List<V> chunks). Also note that process(List<V> chunks) is executed on EDT.

doInBackground() 返回, done() EDT ,你可以覆盖它以用于任何GUI更新。您还可以检索从 http://docs.oracle.com/javase/6/docs/api/javax/swing /SwingWorker.html#get%28%29\"rel =nofollow noreferrer> 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 是您传递给 进程(列出< V> chunk) 通过 发布(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中的并发