How to pan a JavaFX LineChart

吃可爱长大的小学妹 提交于 2019-12-11 16:57:29

问题


In JavaFx I have a LineChart lc for which I create and add a series,

lc.getData().addAll(series1);

It displays just fine, but seems to sample all data points to fit the whole domain into the chart.

Is there a way to force the LineChart to just display the last 10 data points, say, of the series?

Ultimately I would like to create a way to pan the chart contents so that a window of the data is displayed, as a function of pan position.

I found this SO post but it removes data, which means I would then need to add it back. I would rather keep all data in the series if possible, and set the usable range of that series if possible.


回答1:


I worked out the solution myself using the standard fx libraries.

So long as the horizontal axis is a NumberAxis, you can use the setLowerBound() and setUpperBound() functions.

Combined with a scrollbar this works perfectly.

For example,

    final static int MAX_DISPLAY = 100
    LineChart<Number, Number> lineChart;
    ScrollBar scroller;

    scroller.setMin(0);
    scroller.setMax(1000 - MAX_DISPLAY);

    scroller.valueProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number number, Number t1) {

            double pos = scroller.getValue();

            NumberAxis na = (NumberAxis)lineChart.getXAxis();
            na.setLowerBound(pos);
            na.setUpperBound(pos + MAX_DISPLAY);
        }
    });

Note - if using Scene Builder, your LineChart x-axis will default to CatergoryAxis, so make sure to edit the .fxml file and change it to NumberAxis manually.

Additionally, for my use case since the x-axis represents Unix epoch times, you can convert the Number values into something else using the following code (in my case a date formatted string),

        NumberAxis xAxis = (NumberAxis)lineChart.getXAxis();

        xAxis.setTickLabelFormatter(new StringConverter<Number>() {

            @Override
            public String toString(Number object) {

                return convertToDate(object.longValue());
            }

            @Override
            public Number fromString(String string) {
                return 0;
            }
        });


来源:https://stackoverflow.com/questions/55889947/how-to-pan-a-javafx-linechart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!