You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaFX饼图的图例设置为垂直显示?

JavaFX饼图图例垂直排列的实现方法

当然可以实现图例的垂直排列啦!下面给你两种可行的方案,一种是修改默认图例的布局,另一种是自定义图例,你可以根据需求选择:

方案一:修改默认图例的布局(简单快捷)

JavaFX的PieChart默认图例是用FlowPane来布局的,默认方向是水平,我们只需要修改这个布局容器的排列方向就能切换成垂直。结合你的代码,只需要添加几行关键代码:

ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
if (jsonObject != null){
    pieChartData = FXCollections.observableArrayList(
        new PieChart.Data("Mortgage", mortgageValue),
        new PieChart.Data("Security", securityValue),
        new PieChart.Data("Others", remainingValue));
}
final PieChart chart = new PieChart(pieChartData);

// 核心修改代码
Legend legend = chart.getLegend();
if (legend != null) {
    // 获取图例内部的FlowPane布局容器
    FlowPane legendLayout = (FlowPane) legend.getChildren().get(0);
    // 设置布局方向为垂直
    legendLayout.setOrientation(Orientation.VERTICAL);
    // 可选:调整间距和对齐方式,优化显示效果
    legendLayout.setVgap(6); // 垂直间距
    legendLayout.setAlignment(Pos.CENTER_LEFT);
}

原理很简单:默认图例的项是由FlowPane管理的,把它的orientation属性改成VERTICAL,就能让图例项从上到下垂直排列了。

方案二:自定义图例(灵活性更高)

如果你想要更自由地控制图例的样式(比如调整颜色块大小、字体、间距等),可以隐藏默认图例,自己用VBox构建一个垂直排列的自定义图例:

ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
if (jsonObject != null){
    pieChartData = FXCollections.observableArrayList(
        new PieChart.Data("Mortgage", mortgageValue),
        new PieChart.Data("Security", securityValue),
        new PieChart.Data("Others", remainingValue));
}
final PieChart chart = new PieChart(pieChartData);

// 隐藏默认图例
chart.setLegendVisible(false);

// 构建自定义垂直图例
VBox customLegend = new VBox(8); // 设置每个图例项之间的垂直间距
customLegend.setPadding(new Insets(10, 10, 10, 10));

// 为每个饼图数据创建对应的图例项
for (PieChart.Data data : pieChartData) {
    HBox item = new HBox(5); // 颜色块和标签的水平间距
    // 创建颜色方块
    Rectangle colorBlock = new Rectangle(16, 16);
    colorBlock.setFill(data.getNode().getStyleableProperty("-fx-pie-color").getValue());
    // 创建标签
    Label label = new Label(data.getName());
    item.getChildren().addAll(colorBlock, label);
    customLegend.getChildren().add(item);
}

// 把自定义图例和饼图放到布局容器中(比如BorderPane)
BorderPane root = new BorderPane();
root.setCenter(chart);
root.setRight(customLegend); // 图例放在右侧,垂直排列

这种方式可以完全按照你的需求定制图例的外观,比如给标签加样式、调整颜色块的圆角等等。

内容的提问来源于stack exchange,提问作者V.Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:53:33