你的问题是在这里:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
theButton.setText("Trying to connect...");
theButton.setEnabled(false);
theButton.repaint();
// doing some IO operation which takes few seconds // **********
theButton.setText("connected (click to disconnect)");
theButton.setEnabled(true);
theButton.repaint();
}
});
- 标有
*******
评论的代码在运行EDT,将比分扳成了冰点你的应用程序和所有的绘画。
- 改为使用SwingWorker在后台线程中运行代码。
- 请注意,ActionListener中的代码不需要使用
invokeLater(...)
,因为此代码默认情况下已在EDT上运行。
- 也摆脱你的
repaint()
电话,因为他们不需要,他们不帮助。
- 为您的SwingWorker添加一个PropertyChangeListener来监听它何时完成,然后您可以重置您的JButton。
而是做:
// code not compiled nor tested
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
theButton.setText("Trying to connect...");
theButton.setEnabled(false);
MySwingWorker mySwingWorker = new MySwingWorker();
mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {
// listen for when SwingWorker's state is done
// and reset your button.
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
theButton.setText("connected (click to disconnect)");
theButton.setEnabled(true);
}
}
});
mySwingWorker.execute();
}
});
和
// code not compiled nor tested
public class MySwingWorker extends SwingWorker<Void, Void> {
@Override
public void doInBackground() throws Exception {
// doing some IO operation which takes few seconds
return null;
}
}
而且一定要阅读:Concurrency in Swing。
后台工作人员和异步事件。 – user2246674