Swing GUI 下的漫长过程:意外延迟 [英] Long process under Swing GUI : unexpected delay
问题描述
在这里解释我的问题是一个 MCVE,其中单击 JDialog
上的 JButton
A 将打开 JDialog
B:
To explain my question here is an MCVE where clicking clicking a JButton
on JDialog
A opens JDialog
B:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
public class DiagA extends JDialog {
private DiagB diag;
public DiagA() {
super();
setTitle("main diag");
setSize(200, 150);
setLocation(400,400);
JButton btn = new JButton("Show DiagB");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
showDiag();
}
});
add(btn, BorderLayout.NORTH);
//make main frame visible
setVisible(true);
}
void showDiag() {
if(diag == null) {
diag = new DiagB();
//this prints out as expected
System.out.println("set visible done");
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {}
//only after the delay diag shows in full
}
}
public static void main(String[] args) {
new DiagA();
}
}
class DiagB extends JDialog {
public DiagB() {
super();
setTitle("2nd diag");
setSize(150, 100);
setLocation(600,420);
setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().setBackground(Color.YELLOW);
setVisible(true);
}
}
正如您在代码中看到的,我在创建 DiagB
后添加了 3 秒延迟.单击按钮 DiagB
显示如下:
As you can see in the code I added a 3 sec delay after creating DiagB
.
Clicking the button DiagB
shows like this:
只有在 3 秒延迟结束后,DiagB
才完整显示:
Only after the 3 sec delay ends, DiagB
shows in full:
我的问题是:
一个.为什么DiagB
在构造后没有完全显示?(仅当 showDiag()
返回时才完整显示).
b.我的问题的原因是 DiagB
需要通过 DiagA
中的长过程进行更新.
正确的更新方式是什么?是否需要为每个更新过程使用 SwingWorker
?
My questions are:
a. Why doesn't DiagB
show completely after it is constructed ? (It shows in full only when showDiag()
returns).
b. The reason for my question is that DiagB
needs to be updated, by long processes in DiagA
.
What is the right way to update ? Does it require using a SwingWorker
for every updating process ?
推荐答案
a.showDiag
在 GUI 线程上运行.当您使 GUI 线程休眠时,GUI 将完全死亡.
a. showDiag
runs on the GUI thread. The GUI will be completely dead while you make the GUI thread sleep.
B.是的,将 SwingWorker
用于长时间运行的任务,并使用 SwingUtilities.invokeLater()
将 GUI 更新任务提交回 GUI 线程.或者,实现 SwingWorker#done()
,这是一种在 SwingWorker
任务完成后在 GUI 线程上运行的便捷方法.
b. Yes, use a SwingWorker
for long-running tasks and use SwingUtilities.invokeLater()
to submit GUI-updating tasks back to the GUI thread. Alternatively, implement SwingWorker#done()
which is a convenience method that runs on the GUI thread after the SwingWorker
task completes.
这篇关于Swing GUI 下的漫长过程:意外延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!