在不记住数据的情况下重新创建条形图

Recreate bar chart without it remembering data

任务

我有一个条形图,我必须一遍又一遍地填充不同的数据。数据必须按预定义的顺序排列。当然我只想改变数据,而不是每次都创建条形图。

问题

一旦你有一个给定名称的类别已经存在于早期数据中,那么顺序就是错误的。

我创建了一个例子。通过单击 "Insert Before" 按钮,添加给定数量的柱。之后添加 "static" 栏。

"Insert After" 按钮先添加 "static" 条,然后再添加其他条。

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);
    }
}

当您启动程序并单击 "Insert Before" 时,您会看到:

当您重新启动程序并单击 "Insert After" 时,您会看到:

当您重新启动程序并单击 "Insert Before",然后单击 "Insert After" 时,您会看到:

这是错误的。应该是这样的:

有没有办法清除条形图的内存?显然 setData 是不够的。

我怀疑是柱状图的特殊删除方式有关,添加新数据时数据没有完全删除。在 JavaFX 中的条形图 class 的源代码中有一些可疑的方法,例如 "seriesBeingRemovedIsAdded"。

非常感谢您的帮助!

嗯..再次调用 layout() 似乎解决了问题

bc.getData().clear();
bc.layout();
bc.getData().addAll( series1 );

在 "Insert After" 第二个循环中。