【问题标题】:javaFX UI crashes when using an infinte loop [duplicate]使用无限循环时javaFX UI崩溃[重复]
【发布时间】:2017-09-27 17:48:48
【问题描述】:

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

我听说我可以使用一种叫做线程的东西,但我真的不明白如何正确实现它。

【问题讨论】:

标签: java loops javafx crash


【解决方案1】:

看起来您在 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.
    }
});

【讨论】:

    【解决方案2】:

    这是完全合理的。永远不要阻塞主线程!使用额外的线程来实现您的目标。

    Task<Void> workingTask = new Task<Void>() {
        @Override
        public Void call() {
    
        while (true) {
            //yourcode
        }
    
    }
    

    并使用 Platform.runLater(()-> { //yourcode});为了将小任务发送到主 javafx 线程。例如

    Platform.runLater(() -> {
        mins.setText(Integer.toString(time.getMinutes()));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-31
      • 2016-06-19
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多