Java 如何每秒更改一个类的值?
我是Java新手,我不知道如何在类中每秒减去一个值,在本例中,我尝试使用swing和Java.util的计时器,但失败了 我需要的是在一个JPanel中显示一个倒计时计时器,NivelCronometrado有时间开始,并且一个JPanel包含这个类 我在JPanel中创建了一个JLabel来显示这一次 这是NivelCronometrado的代码 编辑:这是我的一个尝试的代码Java 如何每秒更改一个类的值?,java,swing,timer,countdown,countdowntimer,Java,Swing,Timer,Countdown,Countdowntimer,我是Java新手,我不知道如何在类中每秒减去一个值,在本例中,我尝试使用swing和Java.util的计时器,但失败了 我需要的是在一个JPanel中显示一个倒计时计时器,NivelCronometrado有时间开始,并且一个JPanel包含这个类 我在JPanel中创建了一个JLabel来显示这一次 这是NivelCronometrado的代码 编辑:这是我的一个尝试的代码 else if (this.nivel instanceof NivelCronometrado) {
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()));
}
可能重复
下面是您可以在JPanel中调用的代码片段
Timer timer = new Timer(1000, new TimerListener());
class TimerListener implements ActionListener {
int elapsedSeconds = 30;
public void actionPerformed(ActionEvent evt){
elapsedSeconds--;
timerLabel.setText(elapsedSeconds)
if(elapsedSeconds <= 0){
timer.stop();
wrong()
// fill'er up here...
}
}
}
Timer Timer=new Timer(1000,new TimerListener());
类TimerListener实现ActionListener{
内延时秒=30;
已执行的公共无效操作(操作事件evt){
飞逝秒--;
timerLabel.setText(elapsedSeconds)
如果(elapsedSeconds)“我试图使用swing和java.util的计时器,但我失败了。”您尝试(1)实现它的地方在哪里,您到底是如何失败的?1)“尝试”指的是(最小完整的可验证示例)或(简短、自包含、正确的示例)与不可编译、断章取义的代码片段相反。我做了编辑,现在它被添加到帖子中。你显然没有阅读或不理解MCVE是什么。答案不是宣布可能重复的地方。新用户无法发表评论是有原因的。等你获得更多的代表后,你才能发表评论。
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()));
}
Timer timer = new Timer(1000, new TimerListener());
class TimerListener implements ActionListener {
int elapsedSeconds = 30;
public void actionPerformed(ActionEvent evt){
elapsedSeconds--;
timerLabel.setText(elapsedSeconds)
if(elapsedSeconds <= 0){
timer.stop();
wrong()
// fill'er up here...
}
}
}