我在 JFrame
中有一个保存按钮;单击保存时,“保存”文本设置为“保存....”;我需要在延迟 10 秒后将该文本设置为“已保存”。在 Java 中怎么可能?
请帮助...
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
这就是我所做的...但这不会在延迟的时间内显示为“节省”。
最佳答案
如果你想向用户提供一些正在发生的事情的视觉反馈(并且可能给出一些关于进展的提示)然后去 JProgressBar
和 SwingWorker
(more details)。
另一方面,如果您想遇到一种情况,即当用户单击按钮并且任务应该在后台运行(而用户在做其他事情),那么我将使用以下方法:
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
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();
}
});
关于java - 要在 java 中设置按钮点击延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10084884/