top of page

Line Chart Using JAVAFX

In this example we are seeing how to develop Line Chart application using technologies JavaFX.


A line chart or line graph displays information as a series of data points (markers) connected by straight line segments. A Line Chart shows how the data changes at equal time frequency.

In JavaFX, a line chart is represented by a class named LineChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a LineChart node in JavaFX.


Line.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.chart.CategoryAxis?>
<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane prefHeight="500.0" prefWidth="500.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/11.0.1" fx:controller="application.LineController">
   <children>
      <LineChart fx:id="lineChart" title="LINE CHART">
        <xAxis>
          <CategoryAxis label="Month" side="BOTTOM" />
        </xAxis>
        <yAxis>
          <NumberAxis label="Salary" side="LEFT" />
        </yAxis>
      </LineChart>
      <Button layoutX="198.0" layoutY="419.0" mnemonicParsing="false" onAction="#generateLineChart" prefHeight="48.0" prefWidth="125.0" text="Generate Line Chart" />
   </children>
</AnchorPane>

LineController.java
package application;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.XYChart;

public class LineController {
	
	@FXML
	LineChart<String,Number> lineChart;
	
	public void generateLineChart(ActionEvent ae){
		lineChart.getData().clear();
		XYChart.Series<String,Number> series=new XYChart.Series<String,Number>();
		
		series.getData().add(new XYChart.Data<String, Number>("Jan",200));
		series.getData().add(new XYChart.Data<String, Number>("Feb",100));
		series.getData().add(new XYChart.Data<String, Number>("Mar",300));
		series.getData().add(new XYChart.Data<String, Number>("Apr",400));
		series.setName("Month Pay");
		lineChart.getData().add(series);
	}
}

Main.java
package application;
	
import javafx.application.Application;

import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;


public class Main extends Application {
	@Override
	public void start(Stage primaryStage) {
		try {
			Parent root=FXMLLoader.load(getClass().getResource("/application/Line.fxml"));
			Scene scene = new Scene(root);
			scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
			primaryStage.setScene(scene);
			primaryStage.show();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		launch(args);
	}
}


bottom of page