3
I made a chronometer (better to say: a timer) that should be executed when a certain button is clicked. I managed to make the timer, but I can’t close it. After calling it he is timing "forever" rs.
I’d 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 causes 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 clock goes on...
My intention was to stop the clock when I did two minutes. And then the label would change to "Result", because I would call the function 'go' passing as false parameter. Thank you to those who help.
What
view.getLbCronometro
returns? What is line 39 of your code? If, as I’m thinking, it’s the line where you dosetText("Resultado")
, then surely this method is returningnull
.– mgibsonbr
view : visual interface class getLbCronometer: encapsulation of the Jlabel lbCronometer, and it returns the lbCronometer. The line 39 is the timer.stop.
– Higor
Um, I was wrong then... In that case, you’re sure you’re calling the method in the same
Cronometro
that you started before? (i.e. is not creating another instance) Because if on line 39 thetimer
is null, so this can only mean that the first part of the code (in whichcond
istrue
) did not execute [for that instance].– mgibsonbr
I am not instantiating. The more I realized that I was instantiating the timer only within the if, and consequently I would not pick on Else, originating Nullpointerexception. I fixed this little problem, but still. The chronometer doesn’t stop, it goes straight.
– Higor
If you can post the rest of the code so it can be compiled and tested, that would be great! (How is a
NullPointerException
, you will probably discover your error reducing the code so that it fits here... ;)– Daniel