This question already has answers here:
javafx animation looping

(3个答案)


3年前关闭。




我正在尝试在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.
    }
});

07-24 17:54
查看更多