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

如何在JFreeChart中为指定分类标签设置不同字体

解决方案

要给选中的智能手机分类标签设置粗体字体,你需要自定义**X轴(CategoryAxis)**的标签绘制逻辑——因为分类标签的字体是由坐标轴控制的,而非柱状图渲染器(Renderer)。下面是具体实现步骤:

1. 创建自定义分类坐标轴类

继承CategoryAxis,重写标签绘制方法,根据分类索引判断是否为选中项,切换字体:

import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPosition;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class CustomCategoryAxis extends CategoryAxis {
    private ArrayList<Integer> selectedCategories;
    private Font regularLabelFont;
    private Font boldLabelFont;

    public CustomCategoryAxis(String axisLabel, ArrayList<Integer> selected) {
        super(axisLabel);
        this.selectedCategories = selected;
        // 自定义字体:可根据需求调整样式、大小
        this.regularLabelFont = new Font("微软雅黑", Font.PLAIN, 12);
        this.boldLabelFont = new Font("微软雅黑", Font.BOLD, 12);
    }

    @Override
    protected void drawCategoryLabel(String categoryLabel, Rectangle2D labelArea, Graphics2D g2, CategoryLabelPosition position) {
        // 获取当前分类在列表中的索引
        int categoryIndex = getCategories().indexOf(categoryLabel);
        // 判断是否为选中的手机,切换字体
        if (selectedCategories.contains(categoryIndex)) {
            g2.setFont(boldLabelFont);
        } else {
            g2.setFont(regularLabelFont);
        }
        // 调用父类方法绘制标签
        super.drawCategoryLabel(categoryLabel, labelArea, g2, position);
    }
}

2. 替换图表的默认X轴

在创建图表的代码中,获取绘图区并替换默认X轴为自定义坐标轴,传入选中的手机索引列表:

// 假设已创建JFreeChart对象chart
CategoryPlot plot = (CategoryPlot) chart.getPlot();
// 传入你已有的selectedSmartphones列表
CustomCategoryAxis customXAxis = new CustomCategoryAxis("智能手机型号", selectedSmartphones);
// 设置自定义X轴
plot.setDomainAxis(customXAxis);

3. 结合现有高亮逻辑

你的MyBarRenderer已经实现了柱状颜色高亮,自定义坐标轴会同时处理标签字体,两者可完美配合——选中的手机会同时拥有特殊颜色的柱状和粗体的名称标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:27:33