【发布时间】:2015-07-19 16:35:12
【问题描述】:
我是 Java 新手,我不知道如何在类中每秒减去一个值,在这种情况下 NivelCronometrado,我尝试使用 swing 和 java 的 Timer .util 我失败了。
我需要的是在 JPanel 中显示倒数计时器,NivelCronometrado 有时间启动,并且 JPanel 包含此类。
我在 JPanel 中创建了一个 JLabel 来显示这次。
这是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;
}
}
这里是我尝试修改 JLabel 以显示时间的 JPanel 代码的摘录:
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();
}
编辑:这是我尝试的代码之一
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()));
}
【问题讨论】:
-
我进行了编辑,现在已添加到帖子中。
-
您显然没有阅读或不了解 MCVE 是什么..
标签: java swing timer countdown countdowntimer