0

The private code is within a Jbutton that starts a timer upon mouse click. The if-statement near the bottom will not stop the timer, when the elapsed time is equal to the original time, but does not. How do I fix this? Additionally, when I repress the button, the timer accelerates at an increased rate.

import java.awt.*;
import java.util.*;


public class refractiveIndex extends javax.swing.JFrame {

public static int time = 10;
public static int elapsedTime = 0;

private void nextQActionPerformed(java.awt.event.ActionEvent evt) { 

time = 10;
elapsedTime = 0;                                     

    final Timer timer = new Timer();
    TimerTask task = new TimerTask()
    {
        public void run()
                {
                    elapsedTime++;//amount of time passed
                    timeLeft.setText("" + (time - elapsedTime));//int 'time' = 0 (this is time left)
                }
    };

    if(time - elapsedTime == 0)
    {
        timer.cancel();//timer stops after 5 secs
        score1 = 0;//resets score
        question.setText("GAME OVER");
    }

    timer.scheduleAtFixedRate(task, 500, 500);//.5 second delay, rate of .5 second
Ben
  • 321
  • 1
  • 6
  • 21
  • 1
    Imagine I send you a letter, and just after posting it, I assume something about you reading it. Same here, you "submit" a task to the timer, and your test (the `if`) is even before submission. –  Jun 14 '15 at 15:52
  • The how do I display the time decrementing? – Ben Jun 14 '15 at 16:04

1 Answers1

1

You can adapt your custom TimerTask:

TimerTask task = new TimerTask() {
    public void run() {
        elapsedTime++;//amount of time passed
        timeLeft.setText("" + (time - elapsedTime));

        if (time - elapsedTime == 0) {
            cancel();
            score1 = 0;//resets score
            question.setText("GAME OVER");
        }
    }
};

See also this question.

Community
  • 1
  • 1