【发布时间】:2014-04-21 09:59:24
【问题描述】:
这只是 SwingWorker 的一个实现:
class GuiWorker extends SwingWorker<Integer, Integer> {
private JFrame frame = new JFrame();
private JDialog dialog = new JDialog(frame, "Loadin data", true);
private JProgressBar progressBar = new JProgressBar();
private Statistics st = new Statistics();
public GuiWorker(GraphEditor editor, Statistics st) {
this.st = st;
Window mainWindow = SwingUtilities.windowForComponent(editor
.getGraphComponent().getParent());
dialog.setSize(400, 200);
int x = mainWindow.getX() + (mainWindow.getWidth() - dialog.getWidth())
/ 2;
int y = mainWindow.getY()
+ (mainWindow.getHeight() - dialog.getHeight()) / 2;
progressBar.setString("Have fun to wait some time...");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
dialog.add(progressBar);
dialog.setModal(true);
dialog.setLocation(x, y);
dialog.setVisible(true);
}
@Override
protected Integer doInBackground() throws Exception {
st.loadInitialData();
return 0;
}
@Override
protected void done() {
dialog.setVisible(false);
JLabel label = new JLabel("Task Complete");
dialog.getContentPane().remove(progressBar);
dialog.getContentPane().add(label);
dialog.getContentPane().validate();
dialog.setVisible(false);
}
}
diaglog 在我强行关闭之前从不隐藏的问题(任务完成后必须隐藏)。
我注意到loadInitialData() 方法是一种从我的DB 收集一些统计信息的方法,这需要几秒钟。
更新:我确信在我关闭dialog 时会调用done() 方法。
更新: 我使用 GuiWorker 的地方在这里:
mainTabs.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
switch (mainTabs.getSelectedIndex()) {
case 0:
case 1:
case 2: // stats tab
GuiWorker gw = new GuiWorker(editor,st);
gw.execute();
break;
default:
break;
}
}
});
【问题讨论】:
-
请将代码贴在你使用 GuiWorker 的地方
-
@Can'tTell 查看更新:)
标签: java multithreading swing swingworker