我有一个保存按钮JFrame
;单击“保存”时,“保存”文本将设置为“正在保存...”;我需要在延迟 10 秒后将该文本设置为“已保存”。在 java 中这怎么可能?
请帮忙...
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
这就是我所做的......但这不会在延迟的时间内显示为“保存”。
如果您想向用户提供正在发生某事的视觉反馈(并且可能给出一些有关进度的提示),那么请执行JProgressBar http://docs.oracle.com/javase/tutorial/uiswing/components/progress.html and SwingWorker http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html (更多细节 https://stackoverflow.com/questions/5148995/problem-making-a-jprogressbar-update-values-in-loop-threaded).
另一方面,如果您希望出现一种情况,当用户单击按钮并且任务应该在后台运行(当用户执行其他操作时),那么我将使用以下方法:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false); // change text if you want
new SwingWorker<Void, Void>() {
@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特定定时器 http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html:
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();
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)