2017-05-29 149 views
1

我對一個有趣的任務感興趣。我使用另一個更新UI的線程在JavaFx中創建了UI。我從Platform.runLater開始更新。代碼:Javafx從線程更新UI Java 8

private void startUpdateDaemon() { 
    updateUserStatus(); 
    updateTable(); 
} 

private void startUpdateDaemonTask() { 
    Task task = new Task<Void>() { 
     @Override 
     protected Void call() throws Exception { 
      while (true) { 
       Platform.runLater(() -> { 
        startUpdateDaemon(); 
       }); 
       Thread.sleep(1000); 
      } 
     } 
    }; 
    Thread th = new Thread(task); 
    th.setDaemon(true); 
    th.start(); 
} 

@Override 
public void initialize(URL location, ResourceBundle resources) { 
    startUpdateDaemonTask(); 
} 

我也有發生在另一個類,我更新UI:

private void startUpdateDaemonTask() { 
    Task task = new Task<Void>() { 
     @Override 
     protected Void call() throws Exception { 
      while (true) { 
       Platform.runLater(new Runnable() { 
        @Override 
        public void run() { 
         updateGameStatus(); 
        } 
       }); 
       Thread.sleep(1000); 
      } 
     } 
    }; 

    Thread th = new Thread(task); 
    th.setDaemon(true); 
    th.start(); 
} 

所以,最後我有兩個地方跟叫「Platform.runLater」和內部的不同方法。 我的問題是我可以創建只有一個「方法」一次調用「Platform.runLater」併發送到此方法將調用不同的方法?可能我可以用消費者寫完成方法並向他發送方法'startUpdateDaemon()'和'updateGameStatus()'? 非常感謝。

回答

3

您可以爲您的方法添加Runnable參數。這個參數是給你Platform.runLater

private void startUpdateDaemonTask(Runnable runner) { 
    Task task = new Task<Void>() { 
     @Override 
     protected Void call() throws Exception { 
      while (true) { 
       Platform.runLater(runner); 
       Thread.sleep(1000); 
      } 
     } 
    }; 

    Thread th = new Thread(task); 
    th.setDaemon(true); 
    th.start(); 
} 

現在你可以調用這個方法與你的方法引用:

startUpdateDaemonTask(this::startUpdateDaemon); 
startUpdateDaemonTask(this::updateGameStatus); 
+0

非常感謝!好辦法。這就是我需要的。 – Leo