Carol Carol - 5 months ago 50x
Java Question

Javafx Donut Chart in FXML

I want to do a Doughnut/Donut chart on JavaFX and searching I came to this example: Can PieChart from JavaFX be displayed as a doughnut?

I Works really nice, but since I'm using FXML to make my GUI, I can't use this example. First, I tried to add the class as a @FXML var in the controller class of the panel where I want to insert it, but launched errors.

Then, searched in Google to make the DoughnutChart a custom component, but all the examples are based on Panes. Also, If I try to import my donu.jar to SceneBuilder, the window to select a component is empty.

So, my question is: How do I implement this Doughnut Chart on JavaFX when my GUI is made on FXML?

Thanks a lot.


It's hard to tell what the cause of your error is without seeing the FXML and the error message.

I got this to work pretty easily: the one thing to be aware of is that the FXMLLoader instantiates classes by invoking the no-argument constructor. If it can't find one, it tries to use a builder class as a back-up plan. So the one modification you need to make to @jewelsea's DoughnutChart implementation is to add a no-argument constructor. (You could also define a DoughnutClassBuilder, but that's a lot more work, and doesn't get you any extra benefit.) So I did this:

package doughnut ;

// imports as before...

public class DoughnutChart extends PieChart {
    private final Circle innerCircle;

    public DoughnutChart() {

    // everything else as before...


Then the following FXML:

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

<?import javafx.scene.layout.StackPane?>
<?import doughnut.DoughnutChart?>

<StackPane xmlns:fx="" fx:controller="doughnut.SampleController">
    <DoughnutChart fx:id="doughnutChart" />


with the controller

package doughnut;

import javafx.fxml.FXML;
import javafx.scene.chart.PieChart;

public class SampleController {
    private PieChart doughnutChart ;

    public void initialize() {
            new PieChart.Data("Grapefruit", 13),
            new PieChart.Data("Oranges", 25),
            new PieChart.Data("Plums", 10),
            new PieChart.Data("Pears", 22),
            new PieChart.Data("Apples", 30));


and the application class

package doughnut;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {
    public void start(Stage primaryStage) throws Exception {
            StackPane root = (StackPane)FXMLLoader.load(getClass().getResource("DoughnutChartDemo.fxml"));
            Scene scene = new Scene(root,400,400);

    public static void main(String[] args) {

work exactly as expected.