[英]How to disable a JButton for certain period of time?
我想禁用JButton
约10秒钟。 有办法吗?
谢谢
使用Swing Timer
,当触发时,它将在事件调度线程的上下文中通知已注册的侦听器,从而可以安全地从中更新UI。
有关更多详细信息,请参见如何 在Swing中 使用Swing计时器和并发。
首先阅读@MadProgrammer
的答案,并通过那里提供的链接。 如果您仍然需要基于这些建议的可行示例,请参考以下示例。
为什么解决方案比提出的几种解决方案更好
这是因为它使用javax.swing.Timer
来启用按钮,该按钮使GUI相关任务可以在事件调度线程(EDT)上自动执行。 这样可以避免将swing应用程序与非EDT操作混合使用。
请尝试以下示例:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SwingDemo extends JPanel {
private final JButton button;
private final Timer stopwatch;
private final int SEC = 10;
public SwingDemo() {
button = new JButton("Click me to disable for " + SEC + " secs");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton toDisable = (JButton) e.getSource();
toDisable.setEnabled(false);
stopwatch.start();
}
});
add(button);
stopwatch = new Timer(SEC * 1000, new MyTimerListener(button));
stopwatch.setRepeats(false);
}
static class MyTimerListener implements ActionListener {
JComponent target;
public MyTimerListener(JComponent target) {
this.target = target;
}
@Override
public void actionPerformed(ActionEvent e) {
target.setEnabled(true);
}
}
public static void main(String[] args) {
final JFrame myApp = new JFrame();
myApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myApp.setContentPane(new SwingDemo());
myApp.pack();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
myApp.setVisible(true);
}
});
}
}
您可以使用Thread
, Task
或更简单的Timer
类。
您可以使用Thread.sleep(时间以毫秒为单位)
例如:Thread.sleep(10000); //睡眠10秒
JButton button = new JButton("Test");
try {
button.setEnabled(false);
Thread.sleep(10000);
button.setEnabled(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
但它必须在单独的线程中,否则会使所有GUI挂起10秒钟。
您可以发布有关代码的更多详细信息,我可以提供帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.