How to remove the legend of a PieChart in JavaFX?


In the pie chart, we represent the data values as slices of a circle. Each slice is differentiated from other (typically by color). In JavaFX, you can create a pie chart by instantiating the javafx.scene.chart.PieChart class.

By default, a JavaFX pie chart contains labels of the slices and a legend − a bar with colors specifying the category represented by each color.

Making the legend invisible

The PieChart class has a property named legendVisible (inherited from the class Chart). It is of type boolean and, you can set the value to it using the setLegendVisible() method.

By default, the value of the legendVisible property is true, if you set it to false, the legend will be invisible.

Example

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.StackPane;
public class PieChartExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a Pie chart
      PieChart pieChart = new PieChart();
      //Setting data
      ObservableList data = FXCollections.observableArrayList(
      new PieChart.Data("Work", 10),
      new PieChart.Data("Chores", 2),
      new PieChart.Data("Sleep", 8),
      new PieChart.Data("Others", 4));
      pieChart.setData(data);
      //Making the legend invisible
      pieChart.setLegendVisible(false);
      //Creating a stack pane to hold the pie chart
      StackPane pane = new StackPane(pieChart);
      pane.setStyle("-fx-background-color: BEIGE");
      //Setting the Scene
      Scene scene = new Scene(pane, 595, 300);
      stage.setTitle("Pie Chart");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 20-May-2020

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements