Swing 中一些最重要的概念是
不要在事件调度线程 (ETD) 中执行任何长时间运行/阻塞的操作。这将导致 UI 出现“冻结”且无响应。好在,你似乎明白这一点。
不要从除 EDT 之外的任何线程创建或修改任何 ui 组件。你不这样做。
您最好的行动原因是利用SwingWorker
,这允许您执行长时间运行的操作,同时向侦听器提供进度反馈。
public class TestProgress {
public static void main(String[] args) {
new TestProgress();
}
public TestProgress() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
ProgressPane progressPane = new ProgressPane();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(progressPane);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// progressPane.doWork();
}
});
}
public class ProgressPane extends JPanel {
private JProgressBar progressBar;
private JButton startButton;
public ProgressPane() {
setLayout(new GridBagLayout());
progressBar = new JProgressBar();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(progressBar, gbc);
startButton = new JButton("Start");
gbc.gridy = 1;
add(startButton, gbc);
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startButton.setEnabled(false);
doWork();
}
});
}
public void doWork() {
Worker worker = new Worker();
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
progressBar.setValue((Integer) evt.getNewValue());
}
}
});
worker.execute();
}
public class Worker extends SwingWorker<Object, Object> {
@Override
protected void done() {
startButton.setEnabled(true);
}
@Override
protected Object doInBackground() throws Exception {
for (int index = 0; index < 1000; index++) {
int progress = Math.round(((float) index / 1000f) * 100f);
setProgress(progress);
Thread.sleep(10);
}
return null;
}
}
}
}
您的其他选择是使用 a ProgressMonitor
,或者,如果您真的很绝望,请使用SwingUtilities#invokeLater(Runnable)
,但是,我真的鼓励您SwingWorker
改用 ;)