如何用JLabel创建计时器?

时间:2015-11-02 13:09:38

标签: java swing timer

我希望在我的JPanel中显示一个带有计时器的JLabel,例如:

03:50 sec
03:49 sec
....
....
00:00 sec

所以我构建了这段代码:

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

    private boolean isAlive = false;

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

    public void run() {
        int timeInSecond = 185
        int minutes = timeInSecond/60;
        while (isAlive) {
            try {
                //TODO
            } catch (InterruptedException e) {
                log.logStackTrace(e);
            }
        }
    }

}//fine autoclass

使用此代码,我可以启动JLabel

TimeRefreshRace arLabel = new TimeRefreshRace ();
arLabel.start();

所以我有时间在secondo,例如180秒,我该如何创建计时器?

2 个答案:

答案 0 :(得分:1)

您可以在try块内调用事件调度程序线程(EDT)并更新您的UI:

        try {
            SwingUtils.invokeLater(new Runnable() {
                @Override
                public void run() {
                    this.setText(minutes + " left");
                }
            }
            //You could optionally block your thread to update your label every second.
        }

或者,您可以使用Timer而不是实际线程,因此您的TimerRefreshRace将拥有自己的计时器,可定期触发事件。然后,您将在try-catch块中使用相同的代码来更新UI。

答案 1 :(得分:1)

以下是一个如何构建倒计时标签的示例。您可以使用此模式来创建组件。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;

public class TimerTest {

    public static void main(String[] args) {
        final JFrame frm = new JFrame("Countdown");
        final JLabel countdownLabel = new JLabel("03:00");
        final Timer t = new Timer(1000, new ActionListener() {
            int time = 180;
            @Override
            public void actionPerformed(ActionEvent e) {
                time--;
                countdownLabel.setText(format(time / 60) + ":" + format(time % 60));
                if (time == 0) {
                    final Timer timer = (Timer) e.getSource();
                    timer.stop();
                }
            }
        });
        frm.add(countdownLabel);
        t.start();
        frm.pack();
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setVisible(true);
    }

    private static String format(int i) {
        String result = String.valueOf(i);
        if (result.length() == 1) {
            result = "0" + result;
        }
        return result;
    }
}