Stopwatch - Timer

3

I made a stopwatch (ie a timer) that should be executed when a certain button is clicked. I was able to do the timer, but I can not shut it down. After calling it is timing "forever" rs.

I would like you to help me. Code:

package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import view.View;

/**
 *
 * @author Higor
 */
public class Cronometro {

    private View view;
    private Timer timer;
    private ActionListener action;
    private int minutos;
    private int segundos;

    public Cronometro(View view) {
        this.view = view;
    }

    public void go(boolean cond) {
        if (cond == true) {
            action = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    view.getLbCronometro().setText("0" + minutos + " : " + ++segundos + "");
                    if (segundos == 59) {
                        segundos = 0;
                        minutos = 1;
                    }
                }
            };
            timer = new Timer(1000, action);
            timer.start();
        } else {
            view.getLbCronometro().setText("Resultado.");
            timer.stop();
            /**
             * Gera erro aqui, quando eu chamo a função go com parâmetro false.
             * Que seria para encerrar o temporizador.
             */
        }
    }
}

The timer stop generates this error:

Exception in thread "Timer-0" java.lang.NullPointerException
    at controller.Cronometro.go(Cronometro.java:39)
    at controller.Controller$Temporizador$Tempo.run(Controller.java:356)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

And the timer continues ...

My intention was to stop the stopwatch when it took two minutes. And then the label would change to "Result" because I would call it would call the 'go' function passing as a false parameter. Thanks to all who help.

    
asked by anonymous 19.09.2015 / 00:25

1 answer

1

You must put the condition for the stopwatch to stop within the action Ex:

timer = new Timer(1000, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {


        if (/* Cronometro = 2 Minutos */) {
            timer.stop();
            //...Update the GUI...
        }
    }    
});
    
21.09.2015 / 00:09