gpt4 book ai didi

java - 如何在JLabel中显示计时器

转载 作者:行者123 更新时间:2023-11-30 07:33:11 24 4
gpt4 key购买 nike

我想在我的 JLabel 中显示一个计时器。所以我构建了这段代码,它可以工作,但我不知道这段代码是否正确。

public void cswing(){
labelTempoGara = new TimeRefreshRace();
labelTempoGara.start();
}

@SuppressWarnings("serial")
class TimeRefreshRace extends JLabel implements Runnable {

private boolean isAlive = false;

public void start() {
threadTempoCorsa = new Thread(this);
isAlive = true;
threadTempoCorsa.start();
}

public void run() {
int tempoInSecondi = programma.getTempoGara() % 60;
int minuti = programma.getTempoGara() / 60;
while (isAlive) {
try {
if (minuti <= 0 && tempoInSecondi<=1) {
isRun=false;
this.setText("00:00");
isAlive = false;
salvaDatiCorsa();
break;
}
if(tempoInSecondi<=1){
minuti--;
tempoInSecondi=60;
}
--tempoInSecondi;
this.setText(minuti+":"+ tempoInSecondi);
Thread.sleep(1000);

} catch (InterruptedException e) {
log.logStackTrace(e);
}
}

}

public void kill() {
isAlive = false;
isRun=false;
}

}//fine autoclass

我再说一遍,这段代码可以工作,但我不知道是否正确使用 JLabel 和 Runnable 线程

最佳答案

这是使用 javax.swing.Timer 重新设计的示例因为您还没有提供可运行的示例,所以我无法测试它是否有效,但我希望您能够解决问题(如果存在)。

注意不要导入java.util.Timer,它是另一个需要与 Swing 线程同步的类(如示例中的线程)。

class TimeRefreshRace extends JLabel implements ActionListener {

private Timer timer;

public void start() {
timer = new Timer(1000, this);
timer.start();
}

public void actionPerformed(ActionEvent ae) {
int tempoInSecondi = programma.getTempoGara() % 60;
int minuti = programma.getTempoGara() / 60;
if (minuti <= 0 && tempoInSecondi<=1) {
this.setText("00:00");
salvaDatiCorsa();
break;
}
if(tempoInSecondi<=1){
minuti--;
tempoInSecondi=60;
}
--tempoInSecondi;
this.setText(minuti+":"+ tempoInSecondi);

}

public void kill() {
if (timer != null) {
timer.stop()
}
}

}//fine autoclass

关于java - 如何在JLabel中显示计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35770854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com