在我的java应用程序中,我使用swing来实现UI。有一个名为 theButton 的按钮,它在以下及时步骤中参与了一些IO操作:
完成IO操作 theButton 现在读取“已连接(单击以断开连接)”。
-
// theButton with text "Click to connect is clicked"
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
theButton.setText("Trying to connect...");
theButton.setEnabled(false);// to avoid clicking several times! Some users cannot wait
theButton.repaint();
// doing some IO operation which takes few seconds
theButton.setText("connected ( click to disconnect)");
theButton.setEnabled(true);
theButton.repaint();
}
});
答案 0 :(得分:3)
你的问题在这里:
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上运行,并将它冻结你的应用程序及其所有绘画。 invokeLater(...)
代码,因为默认情况下此代码已在EDT上运行。 repaint()
次来电,因为不需要这些电话而且他们没有帮助。取而代之的是:
// 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。