以下MCVE演示了Swing
gui运行一个漫长的过程。长进程在SwingWorker
内运行,因此它不会阻止(冻结)GUI:
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;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
public class DiagA extends JDialog {
private FrameB frame;
private JButton btn;
public DiagA() {
super();
setTitle("main frame");
setSize(200, 150);
setLocation(400,400);
btn = new JButton("Show Frame B");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
show2ndFrame();
}
});
add(btn, BorderLayout.NORTH);
setVisible(true);
}
void show2ndFrame() {
if(frame == null) {
frame = new FrameB();
btn.setText("Exit");
}else {
System.exit(0);
}
doWork();
}
private void doWork() {
SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
try {
for(int i = 1 ; i<=100 ; i++) {
//represents a long process
Thread.sleep(100);
frame.update(i);
}
} catch (InterruptedException ex) {}
return null;
}
};
sw.execute();
}
public static void main(String[] args) {
new DiagA();
}
}
class FrameB extends JFrame {
JLabel label;
public FrameB() {
super();
setTitle("2nd frame");
setSize(150, 100);
setLocation(600,420);
setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().setBackground(Color.YELLOW);
label = new JLabel("0");
add(label);
setVisible(true);
}
void update(int progress) {
label.setText(String.valueOf(progress));
}
}
假设需要通过几个不同的长进程更新FrameB
,
我发现在SwingWorker
内运行每个此类进程都很安静繁琐。
有替代方法吗?