I want to display a timer in my JLabel. So I have build this code, it works, but I don't know if this code is correct.
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
I repeat, this code works, but I don't know if is correct use JLabel with Runnable thread or not
Here is example reworked with javax.swing.Timer
Because you haven't provied a runnable example I cannot test whether it works, but I hope you can fix problems, if they exists.
Attention Don't import java.util.Timer
it's another class which also need synchronization with Swing thread (like thread in your example).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.