时间延迟无法正常工作



在我的程序中,我使用以下代码所做的是在特定的时间间隔(用户提供的时间)内(自动)按下一个按钮一定的次数(从用户那里获取的次数)。但问题是,这有时无法正常工作。我的意思是,如果我把时间设置为1.5秒,然后去做;10次中有9次是在1.5秒的间隙跑的,但第10次我跑的时候,它跑得很快;以不到一秒钟的时间间隔单击按钮。(请注意,10个中有9个只是示例-这不是确切的数字)

代码:

double y = 1000 * (Double.parseDouble(t2.getText()));
int zad = (int)y;
final Timer timer = new Timer(zad, new ActionListener() {
int tick = 0;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Success" + ++tick);
jButton7.doClick();
final int col = Integer.parseInt(t3.getText());;
if (tick >= col) {
((Timer) e.getSource()).stop();
jButton6.setVisible(true);

}
}
});

timer.setInitialDelay(0);
System.out.format("About to schedule task.%n");
timer.start(); 
System.out.format("Task scheduled.%n");

希望我能理解,如果我没有理解,我很抱歉,我是java的新手。如果你不理解我的问题,请问我你在哪里不理解我,我会详细说明这一部分。

更新:我知道是什么时候发生的。看看这个过程是否正在进行,我关闭jframe并单击按钮再次执行,它显示了这个错误。但当我关上那扇窗户时,我希望它停下来。

正如文档中所说:http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html#stop(),方法stop:

Stops the Timer, causing it to stop sending action events to its listeners.

因此,当您调用stop时,将执行最后一个操作。紧接在被调用的那个之后。

您的代码应该是:

double y = 1000 * (Double.parseDouble(t2.getText()));
int zad = (int)y;
final Timer timer = new Timer(zad, new ActionListener() {
int tick = 0;
boolean itsOver=false;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Success" + ++tick);
final int col = Integer.parseInt(t3.getText());
if (! itsOver)
{
jButton7.doClick();
}
if (tick >= col) {
itsOver = true;
((Timer) e.getSource()).stop();
jButton6.setVisible(true);
}
}
});

timer.setInitialDelay(0);
System.out.format("About to schedule task.%n");
timer.start(); 
System.out.format("Task scheduled.%n");

最新更新