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

Vaadin饼图取消所有图例标签后异常,如何限制取消最后一个选中项?

解决Vaadin 3D饼图取消所有图例后的异常问题

要限制用户无法取消最后一个选中的图例项,你可以通过监听图例点击事件,在事件触发时检查当前可见的系列数量,若只剩最后一个,则阻止其被隐藏。以下是修改后的完整代码:

private Component getCompaniesChart() {
    Chart chart = new Chart(ChartType.PIE);
    Configuration conf = chart.getConfiguration();
    DataSeries dataSeries = new DataSeries();
    service.findAllDepartments()
            .forEach(department -> dataSeries.add(new DataSeriesItem(department.getName(), department.getEmployeeCount())));

    Options3d options3d = new Options3d();
    options3d.setEnabled(true);
    options3d.setAlpha(70);
    options3d.setBeta(0);
    conf.getChart().setOptions3d(options3d);

    PlotOptionsPie plotOptions = new PlotOptionsPie();
    plotOptions.setDepth(100);
    plotOptions.setAllowPointSelect(true);
    plotOptions.setShowInLegend(true);
    plotOptions.setShadow(true);
    plotOptions.setSize("200%");

    conf.getLegend().setLabelFormat("{name} ({y})");
    conf.getLegend().setItemMarginTop(100);

    // 添加图例点击事件监听器,限制最后一个图例不能被取消
    chart.addLegendItemClickListener(event -> {
        DataSeriesItem item = dataSeries.get(event.getItemIndex());
        // 统计当前可见的系列数量
        long visibleCount = dataSeries.stream()
                .filter(DataSeriesItem::isVisible)
                .count();
        // 如果当前点击的是最后一个可见项,阻止隐藏
        if (item.isVisible() && visibleCount == 1) {
            event.preventDefault();
        }
    });

    conf.setPlotOptions(plotOptions);
    conf.setSeries(dataSeries);
    conf.getChart().setStyledMode(true);

    return chart;
}

关键逻辑说明:

  • 图例点击监听:通过addLegendItemClickListener捕获用户点击图例的事件
  • 可见数量统计:用流式API统计当前DataSeries中所有可见的DataSeriesItem数量
  • 阻止默认行为:当点击的项是最后一个可见项时,调用event.preventDefault()取消隐藏操作,确保始终至少有一个图例处于选中状态

这样就能避免所有图例取消后饼图出现异常的问题,同时保持正常的图例切换动画。

内容的提问来源于stack exchange,提问作者Enis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:45:47