Daksh Shah
Daksh Shah

Reputation: 3113

Time delay not working properly

In my program what i am doing with the following code, is pressing (automatically) a button in certain time intervals (time provided by the user) for a certain times (number of times taken from the user). But the thing is that this some times fail to work properly. I mean if i set the time to 1.5 seconds and do it; 9 out of 10 times it does at 1.5 second gaps but the 10th time i run it, it rushes fast; clicks the buttons in time intervals less than a second. (Note here 9 out of 10 is just for example - it is not the exact figure)

Code:

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");

Hope i make sense and sorry if i don't, i am new to java. If you don't understand my question please just ask me where you couldn't understand me and i would elaborate that part to you.

Update: I figured out when it happens. See if the process is going on and i close that jframe and click the button to do it again, it shows this error. But when i close that window i want it to stop.

Upvotes: 0

Views: 288

Answers (1)

Oscar Pérez
Oscar Pérez

Reputation: 4397

As said on the docs: http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html#stop(), method stop:

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

So, when you call stop, the last action is performed. Immediately after the one that has been called.

Your code should be:

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");

Upvotes: 2

Related Questions