更新折线图中的值

时间:2014-02-19 09:25:30

标签: java javafx javafx-2 javafx-8

我有一个非常简单的折线图示例。

    public class MainApp extends Application
{

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

    @Override
    public void start(Stage stage)
    {

        setUserAgentStylesheet(STYLESHEET_CASPIAN);

        stage.setTitle("Line Chart Sample");
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Month");

        final LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);

        lineChart.setTitle("Stock Monitoring, 2010");


        series.setName("My portfolio");

        insertLineChartData("Jan", 23);
        insertLineChartData("Feb", 14);
        insertLineChartData("Mar", 15);
        insertLineChartData("Jun", 36);
        insertLineChartData("Jul", 22);
        insertLineChartData("Aug", 45);
        insertLineChartData("Sep", 43);
        insertLineChartData("Oct", 17);
        insertLineChartData("Nov", 29);
        insertLineChartData("Dec", 25);

        Scene scene = new Scene(lineChart, 800, 600);
        lineChart.getData().add(series);

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


    public void insertLineChartData(String name, float value){

        series.getData().add(new XYChart.Data(name, value));

    }

    public void updateLineChartData()
    {

        for (XYChart.Data<String, Number> data : series.getData())
        {
            Number oldValue = data.getYValue();
            data.setYValue(oldValue.intValue() + 5);

        }

    }


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

我想创建Java方法,将值更新为折线图。你能帮我创建这个Java方法吗?

1 个答案:

答案 0 :(得分:2)

您需要使用series来操纵图表数据

public void update() {
    for (XYChart.Data<String, Number> data : series.getData()) {
        Number oldValue = data.getYValue();
        data.setYValue(oldValue.intValue() + 5);

    }
}

你可以通过下一步测试:

    lineChart.setOnMouseClicked(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            update();
        }
    });