I'm some new in Java and I don't know how I can subtract a value every second in a class, in this case NivelCronometrado, I tried to use a Timer of swing and java.util and I failed.
What I need is in a JPanel show a countdown timer, NivelCronometrado has the time to start and a JPanel contains this class.
I create in the JPanel a JLabel to show this time.
Here is the code of NivelCronometrado
import clases.logicas.elementos.Puntaje;
import java.util.ArrayList;
public class NivelCronometrado extends Nivel
{
private int tiempo;
public NivelCronometrado(int argTiempo, int argId, int[][] argObstaculos,
int[] argPuntosEstrella, Long argRandomSeed, ArrayList<Puntaje> argPuntajes)
{
super(argId, argObstaculos, argPuntosEstrella, argRandomSeed, argPuntajes);
this.tiempo = argTiempo;
}
public void disminuirTiempo()
{
this.tiempo--;
}
public int getTiempo()
{
return this.tiempo;
}
}
And here an extract of the code of the JPanel where I try to modify a JLabel to show the time:
public void establecerNivel()
{
this.setTextTitulo("Nivel " + this.nivel.getId());
this.setTextPuntosValor("0");
if (this.nivel instanceof NivelRestringido) {
this.setTextEspecialTexto("Movimientos:");
NivelRestringido nivelRestringido = (NivelRestringido)this.nivel;
this.setTextEspecialValor(Integer.toString(nivelRestringido.getIntentos()));
}
else if (this.nivel instanceof NivelCronometrado) {
this.setTextEspecialTexto("Tiempo:");
NivelCronometrado nivelCronometrado = (NivelCronometrado)this.nivel;
/*Here subtract time to nivelCronometrado every second*/
this.setTextEspecialValor(Integer.toString(nivelCronometrado.getTiempo()));
}
this.setTextEstrellaValor1(Integer.toString(this.nivel.getPuntosEstrella()[0]));
this.setTextEstrellaValor2(Integer.toString(this.nivel.getPuntosEstrella()[1]));
this.setTextEstrellaValor3(Integer.toString(this.nivel.getPuntosEstrella()[2]));
this.repaint();
}
Edit: Here is the code of one of my attemps
else if (this.nivel instanceof NivelCronometrado) {
this.setTextEspecialTexto("Tiempo:");
NivelCronometrado nivelCronometrado = (NivelCronometrado)this.nivel;
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
nivelCronometrado.disminuirTiempo();
}
};
new Timer(1000, taskPerformer).start();
this.setTextEspecialValor(Integer.toString(nivelCronometrado.getTiempo()));
}