gpt4 book ai didi

java - 每秒用多线程更新 JLabel

转载 作者:行者123 更新时间:2023-12-01 09:06:17 24 4
gpt4 key购买 nike

我尝试减少线程计数,我想在我的 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);

最佳答案

为什么要使用Thread?

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

请参阅本教程 here

希望这有帮助:)

关于java - 每秒用多线程更新 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41256758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com