繁体   English   中英

如何在JLabel中显示计时器

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM