Anu*_*dha 4 java concurrency swing timer
我有一个保存按钮JFrame;点击时将"保存"文本设置保存为"保存...."; 我需要在延迟10秒后将该文本设置为"已保存".如何在Java中实现?请帮忙...
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
这就是我所做的......但是在这段延迟的时间里,这不会表现为"拯救".
如果你想为用户提供视觉反馈的东西是怎么回事用户(可能提供有关进展情况有些淡淡的),然后去JProgressBar和SwingWorker(更多详细信息).
另一方面,如果您想要出现这种情况,当用户单击该按钮并且该任务应该在后台运行时(当用户执行其他操作时),那么我将使用以下方法:
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();
}
});
Run Code Online (Sandbox Code Playgroud)
最后,使用Swing特定计时器的初始解决方案:
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();
}
});
Run Code Online (Sandbox Code Playgroud)