[英]How display timer in 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與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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.