在JavaFX中将动态数据添加到StackedAreaChart

时间:2015-09-17 06:32:12

标签: java javafx-8

我正在尝试动态更改StackedAreaChart的数据。所以我为它创建了一个fxml文件和一个控制器。

enter image description here

fig.fxml

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="495.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.gollahalli.test.controller">
   <children>
      <StackedAreaChart fx:id="graph" layoutX="24.0" layoutY="95.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
        <xAxis>
          <NumberAxis side="BOTTOM" />
        </xAxis>
        <yAxis>
          <NumberAxis side="LEFT" />
        </yAxis>
      </StackedAreaChart>
      <TextField fx:id="number" layoutX="57.0" layoutY="39.0" />
      <Button fx:id="button" layoutX="330.0" layoutY="39.0" mnemonicParsing="false" text="Button" />
   </children>
</AnchorPane>

Controller.java

public class controller {

    @FXML
    private Button button;
    @FXML
    private TextField number;
    @FXML
    private StackedAreaChart<Number, Number> graph;

    public void initialize(){


        XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();

        button.setOnAction(event -> {
            int number1 = Integer.parseInt(number.getText());
            System.out.println(number1);

            for (int i = 0; i < number1; i++) {
                series.getData().addAll(new XYChart.Data(i, i));
            }
            graph.getData().add(series);

        });
    }

}

当我输入数字100时,我能够正确地获取图表,当我更改数据时说101并单击按钮我得到错误为Exception in thread "JavaFX Application Thread" java.lang.IllegalArgumentException: Duplicate series added

我知道要克服这个问题,我必须使用ObservableList,但我不确定如何使用它。

现在问题是,每次点击按钮我应该如何更改/刷新数据?

1 个答案:

答案 0 :(得分:2)

异常消息很明确。为了避免它只添加一次系列:

public void initialize(){
    XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();
    // add series only once at init
    graph.getData().add(series);

    button.setOnAction(event -> {
        int number1 = Integer.parseInt(number.getText());
        System.out.println(number1);

        // clear current data
        series.getData().clear();

        // add new data
        for (int i = 0; i < number1; i++) {
            series.getData().add(new XYChart.Data(i, i));
        }
    });
}