2017-05-18 37 views
0

我在更新JavaFX UI時遇到問題 - 我想在已經顯示的場景中更新線條圖和一些標籤。 我的任務是做一些計算(在其他類中調用返回數據的函數)並將更新後的系列添加到圖表。JavaFX中的實時更新LineChart

下面的代碼(這是一個循環)會出現什麼我想要做的:

//double x - x value of the point i want to add to my chart 
//double y - y value of the point i want to add to my chart 
//string s - some result from function 
mySeries.getData().add(new XYChart.Data(x, y)); 
someLabel.setText(s); 

我的程序凍結,一段時間後,只給出最終的解決辦法,但我希望看到在點圖表完全在添加之後,而不是在執行結束時。如果進程太快,我想添加Thread.sleep(1000),然後將下一個點添加到圖表。

我知道它與線程,併發和任務有關,但我還沒有找到解決方案。我試圖使用我在這裏找到的一些代碼,但仍然不知道正確的答案。

+0

你正在做大量的工作在主線程上。 – Sedrick

回答

1

每個用戶動作,例如,點擊一個按鈕,會在UI線程中通知你的動作監聽器。 UI線程中的邏輯應該儘可能快。我認爲你正在對用戶事件作出反應,然後在UI線程中執行長時間運行的任務。嘗試把你的代碼放在後臺線程中。此外,您需要將UI更新再次放回到UI線程中。你可以用「Platform.runLater(...)」來做到這一點。

事情是這樣的:

public class Test extends Application { 

    public static void main(String[] args) { 
     launch(args); 
    } 

    @Override 
    public void start(Stage primaryStage) throws Exception { 
     Scene scene = new Scene(createChart()); 
     primaryStage.setScene(scene); 
     primaryStage.setHeight(800); 
     primaryStage.setWidth(1200); 
     primaryStage.show(); 
    } 

    private Parent createChart() { 
     LineChart<Number, Number> lc = new LineChart<>(new NumberAxis(), new NumberAxis()); 
     XYChart.Series<Number, Number> series = new XYChart.Series<>(); 
     lc.getData().add(series); 

     new Thread(() -> { 
      try { 
       Thread.sleep(5000); 
       for (int i = 0; i < 15; i++) { 
        int finalI = i; 
        Platform.runLater(() -> series.getData().add(new XYChart.Data<>(1 + finalI, 1 + finalI))); 
        Thread.sleep(1000); 
       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     }).start(); 

     return lc; 
    } 

}