我正在尝试使用 Swing Timer 将程序停止一秒钟。
Timer timer = new Timer(10000,
new ActionListener(public void actionPerformed(ActionEvent e) {}));
没用
public class Card extends JButton implements ActionListener {
int numberClick = 0;
public card() {
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
numberClick++;
if(numberClick == 2) {
Timer timer = new Timer(10000, );
timer.start();
numberClick = 0;
}
}
}
最佳答案
您似乎对计时器的工作原理缺乏基本了解。请阅读How to Use Swing Timers 。这个概念相当简单。
Timer
构造函数中的第一个参数是延迟
。看来你已经把那部分放下了。第二个参数是用于监听“计时器事件”(实际上是 ActionEvents)的 ActionListener
。每次延迟时间都会触发一个事件。回调 (actionPerformed
) 包含在延迟(勾选)之后应执行的操作。因此,无论您希望在那一秒之后发生什么,请将其放入计时器的 ActionListener
的 actionPerformed
中。
此外,如果您只希望它发生一次,您应该调用timer.setRepeats(false);
。另请注意,您使用的是 10000
,单位是毫秒,因此是 10 秒,而不是 1。您应该将其更改为 1000
示例流程
JButton button = new JButton("Press Me");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Timer timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Print after one second");
}
});
timer.setRepeats(false);
timer.start();
}
});
Press Button → Wait One Second → Print Statement
关于java - 如何使用 Swing 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26706639/