要在java中设置单击按钮的延迟?
我在 JFrame
中有一个保存按钮;点击将保存文本集保存到保存....;我需要将该文本设置为保存经过10秒的延迟。在Java中是可能的吗?
请帮助...
I have a save button in a JFrame
;on clicking save the 'save' text sets to 'saving....'; I need to set that text as 'saved' after a delay of 10 seconds.How is it possible in java?
Please help...
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
这是我做的...但这不会显示为在该延迟时间期间。
This is what i did...but this wont shows as 'saving' during that delayed time.
如果您想向用户提供视觉反馈,以了解进度(可能给出一些进度提示)然后访问 JProgressBar
和 SwingWorker
(更多详情)
If you want to provide the user with visual feedback that something is going on (and maybe give some hint about the progress) then go for JProgressBar
and SwingWorker
(more details).
如果在另一方面,你想有一种情况,当用户点击按钮,而任务应该在后台运行(而用户做其他事情),那么我将使用以下方法:
If on the other hand you want to have a situation, when user clicks the button and the task is supposed to run in the background (while the user does other things), then I would use the following approach:
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
特定计时器:
Finally, the initial solution that was using the 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();
}
});