2015-05-05 87 views
0

任務重新創建柱狀圖沒有它,記住數據

我有一個BARCHART我不得不一遍又一遍地填寫不同的數據。數據必須按照預定義的順序。當然,我只想更改數據,而不是每次都創建條形圖。

問題

一旦你與已經在早期的數據存在一個給定的名稱類別,順序是錯誤的。

我創建了一個例子。通過點擊「Insert Before」按鈕,添加給定數量的條。之後,添加「靜態」欄。

「插入後」按鈕首先添加「靜態」欄,然後添加其他欄。當您重新啓動該程序,然後單擊「插入後」,你得到這個

enter image description here

public class BarChartSample extends Application { 

    int count = 1; 

    @Override 
    public void start(Stage stage) { 

     final CategoryAxis xAxis = new CategoryAxis(); 
     final NumberAxis yAxis = new NumberAxis(); 
     final BarChart<String, Number> bc = new BarChart<String, Number>(xAxis, yAxis); 
     bc.setAnimated(false); 

     // create new chart data where the data are inserted before the "static" bar 
     Button insertBeforeButton = new Button("Insert Before"); 
     insertBeforeButton.setOnAction(e -> { 

      XYChart.Series series1 = new XYChart.Series(); 

      for (int i = 0; i < count; i++) { 
       series1.getData().add(new XYChart.Data("New " + i, 50)); 
      } 

      series1.getData().add(new XYChart.Data("Static", 100)); 

      bc.getData().setAll(series1); 

      count++; 

     }); 

     // create new chart data where the data are inserted after the "static" bar 
     Button insertAfterButton = new Button("Insert After"); 
     insertAfterButton.setOnAction(e -> { 

      XYChart.Series series1 = new XYChart.Series(); 

      series1.getData().add(new XYChart.Data("Static", 100)); 

      for (int i = 0; i < count; i++) { 
       series1.getData().add(new XYChart.Data("New " + i, 50)); 
      } 

      bc.getData().setAll(series1); 

      count++; 

     }); 

     // borderpane for chart and toolbar 
     BorderPane bp = new BorderPane(); 
     bp.setCenter(bc); 

     // toolbar 
     HBox hb = new HBox(); 
     hb.getChildren().addAll(insertBeforeButton, insertAfterButton); 
     bp.setTop(hb); 

     Scene scene = new Scene(bp, 400, 200); 

     stage.setScene(scene); 
     stage.show(); 
    } 

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

當您啓動程序,然後單擊「插入之前」,你會得到這樣的:

enter image description here

當您重新啓動該程序,然後單擊「插入之前」,然後在「插入後」,你將會得到:

enter image description here

這是不對的。它應該是這樣的:

enter image description here

有沒有辦法清除條形圖的記憶是什麼?顯然setData是不夠的。

我懷疑它與條形圖中的特殊刪除方法有關,並且在添加新數據時數據未完全刪除。在JavaFX的BarChart類的源代碼中有一些可疑的方法,如「seriesBeingRemovedIsAdded」。

非常感謝您的幫助!

+0

'Insert Before'行爲將在最後一欄之前添加一個欄,即靜態欄。 「插入後」將在最後一欄之後添加一個欄,即再次爲「靜態」。邏輯似乎對我來說是正確的。我不明白'Insert Before'和'Insert After'是如何按下最後一張圖片的。它背後的邏輯是什麼? – ItachiUchiha

+0

這些按鈕被錯誤地命名(「插入」給我意味着你看到的結果),但是代碼的邏輯應該導致最後的圖像;他創建一個新的(空的)系列,然後添加「靜態」,然後添加「新0」,然後添加「新1」。 –

+0

@IchichiUchiha:「Insert Before」應該在「靜態」欄之前添加所有欄。 「插入後」應該添加「靜態」欄後面的所有欄。總之,在靜態之前和靜態之前不應該混合一些酒吧。 – Roland

回答

4

嗯..再次調用layout()似乎解決了問題

bc.getData().clear(); 
bc.layout(); 
bc.getData().addAll(series1); 
在「插入後」第二循環

+0

.clearValues(),不是.clear(),如果你們在談論MPAndroidChart – Odaym