JavaFX 1.2 introduces new Chart APIs. Here we discuss about how to plot line chart using LineChart API.
For creating a chart, we need to create following instance
- Type of Chart – Area, Bar, Bubble, Line, Pie, 3D-Pie, Scatter
- Chart Series – Area, Bar, Bubble, Line, Scatter
- Chart Data – Area, Bar, Bubble, Line, Pie, Scatter
Note: Pie chart is an exception. In this case we don’t need to create instance of Series. Series is required only for X-Y chart types.
Lets implement a Line-Chart which updates its data dynamically. In this case a CPU monitor is simulated by generating random data from java class. The data is generated in a java Thread. The data is sent to JavaFX using a listener interface so as to update the chart. The notification is done via Event Dispatch Thread.
Update: Sample using live CPU and Memory information is available here.
For Applet mode, click on above image
Create an instance of Series to plot chart for CPU usage of user, system and idle:
|
Create an instance of Chart and associate the Series with this chart:
|
A simple UpdateListener interface is created. Which will be used to update data from java to javafx. Dummy CPU data is generated by CPUData class. The update is performed via Event Dispatch Thread using SwingUtilities.invokeLater( <Runnable> ).
|
This update notification is handled in the JavaFX class and we can insert the data in chart as shown below.
|
When the index reaches the upper-bound, we can adjust the lowerBound and upperBound attributes of X-Axis, so as to shift the chart towards left. Also we may remove the initial chart data which are not visible.
Update:
As noted in comments section below, there is some Memory-Leak when we try to continuously update the bounds. Updation of bounds triggers updation of ticks and Skin related code of Label. For now instead of NumberAxis I have used a custom NoTickNumberAxis which supress the tick updates.
|
Try it out and let me know feedback!
Source:


0 Responses to “JavaFX – LineChart”