我正在尝试在 javafx 中构建时钟,但当我尝试使用无限循环时 GUI 崩溃。
while (true) {
Date time = new Date();
// mins and hour are labels
if (time.getMinutes() < 10) {
mins.setText("0" + Integer.toString(time.getMinutes()));
} else {
mins.setText(Integer.toString(time.getMinutes()));
}
if (time.getHours() < 10) {
hour.setText(0 + Integer.toString(time.getHours()));
} else {
hour.setText(Integer.toString(time.getHours()));
}
}
我听说我可以使用称为线程的东西,但我不太明白如何正确实现它。
最佳答案
看起来您正在 UI 线程中使用无限循环。您应该在后台线程中跟踪时间,但在 UI 线程中更新 UI。
要在后台线程中运行,请使用:
new Thread(new Runnable(){
public void run(){
//your code here.
}
}).start();
要在 UI 线程中运行,请使用:
Platform.runLater(new Runnable(){
public void run(){
//your code here.
}
});
关于使用无限循环时 javaFX UI 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46454198/