如何在JLabel中显示计时器
问题描述:
我想在我的JLabel中显示计时器。所以我构建了这段代码,它可以工作,但我不知道这段代码是否正确。如何在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与运行的线程或不
答
我这里是用javax.swing.Timer
返工因为你没有provied一个可运行的例子我无法测试它是否有效,但我希望你能解决问题,如果它们存在的话。
注意不要导入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
+0
谢谢,你的代码作品 – bircastri
使用javax.swingTimer Luke。在Swing线程(Event Dispatcher Thread)之外修改swing组件会产生无法解释的问题。 –