每秒用多线程更新JLabel

时间:2016-12-21 06:49:44

标签: java multithreading

我尝试让线程倒计时,我想在我的Jlabel中更新此计数,但它总是显示空标签这是我的代码

    public static String all;
private static int sec = 59, hour = 7, min = 59;
@Override
public void run() {
    while (sec > 0) {
        System.out.format("%02d:" + "%02d:" + "%02d\n", hour, min, sec);
        try {
            sec--;
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
        }
        if (sec == 0) {
            if (min == 0) {
                if (hour == 0) {
                    break;
                }
                hour--;
                min = 59;
            }
            min--;
            sec = 59;
        }
        StringBuilder builder = new StringBuilder();
        builder.append(String.valueOf(hour))
                .append(":")
                .append(String.valueOf(min))
                .append(":")
                .append(String.valueOf(sec));
        all = builder.toString();
        tesmy.myNum(all); //this method send the for my gui the time every second
    }
}
 }

我确定他发送时间正确,但我不知道如何每秒更新我的标签 我在线上玩这个课 这是我的Jlabel

JLabel jLabel = new JLabel();
    jLabel.setBounds(175, 170, 70, 20);
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            jLabel.setText(myString);
        }
    });

    add(jLabel);

1 个答案:

答案 0 :(得分:1)

为什么要使用Thread?

Java提供Swing Timer来每秒更新标签的文本。

请参阅本教程here

希望这会有所帮助:)