How can I make a dynamic line chart with JavaFX us

2020-04-23 02:44发布

问题:

I have written some code that reads a socket input and outputs the data that I want in an ArrayList of Double values. I would like to keep updating this ArrayList with current values and plot them to a line chart in JavaFx.

How do I set up my javafx file such that it will update the chart as new data is available from the socket?

回答1:

The data in a JavaFX chart is a ObservableList of ObservableLists - one ObservableList for each chart line series. The chart listens to changes on the observable lists of data and, when you modify any of the data in any of these ObservableList (due to the observable nature of them), the chart will automatically update itself. So you don't really need to do much.

Before changing the chart data, set the animated property of your chart to an appropriate value; i.e., turn off animation if you want the new values in the chart to display directly, or turn on animation if you want the data points in the chart to slowly move to the new values.

You state that you are receiving the data over a socket. Usually with traditional socket IO, you have a thread monitoring the socket for new data - this should not be the JavaFX application thread otherwise your application UI will hang while the awaiting new data. When the socket monitoring thread receives new data, it should not modify the the ObservableList for the chart data directly. Instead, it should wrap any modifications to the chart's observable list in a Platform.runLater() call so that the modifications to the chart data occur on the JavaFX application thread.