如果您想向用户提供正在进行某些操作的可视反馈(并且可能会对进度提供一些提示),请转到JProgressBar和SwingWorker(more details)。
另一方面,如果您想要有一种情况,当用户单击按钮并且任务应该在后台运行时(当用户执行其他操作时),那么我将使用以下方法:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false); // change text if you want
new SwingWorker() {
@Override
protected Void doInBackground() throws Exception {
// Do the calculations
// Wait if you want
Thread.sleep(1000);
// Dont touch the UI
return null;
}
@Override
protected void done() {
try {
get();
} catch (Exception ignore) {
} finally {
button.setEnabled(true); // restore the text if needed
}
}
}.execute();
}
});最后,使用Swing specific timer的初始解决方案:
final JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Take somehow care of multiple clicks
button.setText("Saving...");
final Timer t = new Timer(10000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
button.setText("Saved");
}
});
t.setRepeats(false);
t.start();
}
});