延时不能正常工作

时间:2014-01-17 13:53:24

标签: java netbeans

在我的程序中,我正在使用以下代码执行操作,在某些时间间隔(用户提供的时间)按下(自动)按钮一定时间(从用户获取的次数)。但问题是,这有时无法正常工作。我的意思是如果我将时间设置为1.5秒并且这样做;它在10秒的时间内完成了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并单击按钮再次执行此操作,它会显示此错误。但当我关闭那个窗口时,我希望它停止。

1 个答案:

答案 0 :(得分:2)

如文档所述: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");
相关问题