Display additional values in Pie chart

◇◆丶佛笑我妖孽 提交于 2019-11-30 16:06:05

If you have changing values (like in the example code) and/or want to avoid displaying the values in the chart legend, you could modify the text label instead of changing the data names.

Each data item has a text node that holds the string which is shown as the pie chart label. This string can be updated before the chart children are drawn by overriding PieChart#layoutChartChildren:

chart = new PieChart(pieChartData) {
  @Override
  protected void layoutChartChildren(double top, double left, double contentWidth, double contentHeight) {
    if (getLabelsVisible()) {
      getData().forEach(d -> {
        Optional<Node> opTextNode = chart.lookupAll(".chart-pie-label").stream().filter(n -> n instanceof Text && ((Text) n).getText().contains(d.getName())).findAny();
        if (opTextNode.isPresent()) {
          ((Text) opTextNode.get()).setText(d.getName() + " " + d.getPieValue() + " Tons");
        }
      });
    }
    super.layoutChartChildren(top, left, contentWidth, contentHeight);
  }
};

Just bind the pie chart data name to the required value.

pieChartData.forEach(data ->
        data.nameProperty().bind(
                Bindings.concat(
                        data.getName(), " ", data.pieValueProperty(), " Tons"
                )
        )
);

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.*;
import javafx.scene.Group;

public class PieChartSample extends Application {

    @Override public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Imported Fruits");
        stage.setWidth(500);
        stage.setHeight(500);

        ObservableList<PieChart.Data> pieChartData =
                FXCollections.observableArrayList(
                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));
        final PieChart chart = new PieChart(pieChartData);
        chart.setTitle("Imported Fruits");

        pieChartData.forEach(data ->
                data.nameProperty().bind(
                        Bindings.concat(
                                data.getName(), " ", data.pieValueProperty(), " Tons"
                        )
                )
        );

        ((Group) scene.getRoot()).getChildren().add(chart);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!