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

如何在PrimeFaces 13.0.0的BarChartModel柱状图上显示数值?

在PrimeFaces 13.0.0的BarChartModel中显示柱状图数值

你需要通过配置**Chart.js的数据标签插件(chartjs-plugin-datalabels)**来实现这个功能,PrimeFaces 13已经封装了该插件的Java配置类,直接在BarChartOptions中添加插件配置即可。

修改后的完整代码

barModel = new BarChartModel();
ChartData data = new ChartData();

BarChartDataSet barDataSet = new BarChartDataSet();
barDataSet.setLabel("OEE - 24H");

List<Number> values = new ArrayList<>();
List<String> labels = new ArrayList<>();

for(int i=0; i<dc.getDashboardDataList().size(); i++){
    if(dc.getDashboardDataList().get(i).getOee24() != null){
        values.add(dc.getDashboardDataList().get(i).getOee24() * 100);
    }
    else{
        values.add(dc.getDashboardDataList().get(i).getOee24());
    }
    labels.add(dc.getDashboardDataList().get(i).getMachineCodeBC());
}
barDataSet.setData(values);

data.addChartDataSet(barDataSet);
data.setLabels(labels);

barModel.setData(data);

BarChartOptions options = new BarChartOptions();
options.setMaintainAspectRatio(false);
CartesianScales cScales = new CartesianScales();
CartesianLinearAxes linearAxes = new CartesianLinearAxes();
linearAxes.setOffset(true);
linearAxes.setBeginAtZero(true);
CartesianLinearTicks ticks = new CartesianLinearTicks();
linearAxes.setTicks(ticks);
cScales.addYAxesData(linearAxes);
options.setScales(cScales);        

Title title = new Title();
title.setDisplay(true);
title.setText("OEE - 24H");
options.setTitle(title);

Legend legend = new Legend();
legend.setDisplay(true);
legend.setPosition("top");
LegendLabel legendLabels = new LegendLabel();
legendLabels.setFontStyle("italic");
legendLabels.setFontColor("#2980B9");
legendLabels.setFontSize(10);
legend.setLabels(legendLabels);
options.setLegend(legend);

Animation animation = new Animation();
animation.setDuration(0);
options.setAnimation(animation);

// 新增:配置数据标签插件
DataLabels dataLabels = new DataLabels();
dataLabels.setDisplay(true);
// 设置标签位置:可选top/center/bottom/inside/outside等,根据需求调整
dataLabels.setPosition("top");

// 配置标签样式
DataLabelsOptions dlOptions = new DataLabelsOptions();
dlOptions.setColor("#000000"); // 标签颜色
dlOptions.setFontSize(12); // 字体大小
// 可额外扩展配置:字体、对齐方式等
// dlOptions.setFontFamily("Arial");
// dlOptions.setAlign("center");

dataLabels.setOptions(dlOptions);

Plugins plugins = new Plugins();
plugins.setDataLabels(dataLabels);
options.setPlugins(plugins);

barModel.setOptions(options);

关键配置说明

  • DataLabels.setPosition():控制数值显示位置,比如top(柱子上方)、center(柱子内部居中)、bottom(柱子底部),可匹配你的效果图需求选择。
  • DataLabelsOptions:自定义标签的颜色、字体大小、样式等,适配UI设计。
  • 该插件是PrimeFaces 13内置支持的,无需额外引入前端依赖,通过Java模型类配置即可直接生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:07:47