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

如何在JavaFX的BarChart中为每个柱子显示标签?重叠问题求助

JavaFX BarChart类别标签重叠问题解决

我想要在JavaFX的BarChart中为每个数值显示对应的类别标签,但目前所有类别标签都重叠在一起。

现有代码

String query = "";
String destination = "";
try{
    if(classe.isSelected()){
        PreparedStatement tableToGraph = con.prepareStatement(
                "SELECT  libelle_classe,avg(numseance) FROM Absence JOIN Etudiant on Etudiant.id_etudiant=Absence.id_etudiantA Join Classe on Etudiant.id_classeE=Classe.id_classe Group by libelle_classe"
        );
        ResultSet resultSet = tableToGraph.executeQuery();
        ArrayList<Double> numseance = new ArrayList<Double>();
        ArrayList<String> libelle_classe = new ArrayList<String>();
        while (resultSet.next()) {
            libelle_classe.add(resultSet.getString(1));
            numseance.add(resultSet.getDouble(2));
        }
        resultSet.close();
        for (int i = 0; i < numseance.size(); i++) {
            System.out.println(libelle_classe.get(i));
        }
        XYChart.Series<String, Double> dataSeries = new XYChart.Series();
        /*CategoryAxis xAxis = new CategoryAxis();
        xAxis.setLabel("Libelle Classe");
        CategoryAxis yAxis = new CategoryAxis();
        yAxis.setLabel("Avg des absences");*/
        dataSeries.setName("各班级缺勤率");
        for (int i = 0; i < numseance.size(); i++) {
            dataSeries.getData().add(new XYChart.Data(libelle_classe.get(i), numseance.get(i)));
        }
        income_data.getData().add(dataSeries);

解决方法

以下几种方案可以解决标签重叠问题:

  • 旋转X轴标签
    启用并配置CategoryAxis,设置标签旋转角度,让标签倾斜显示避免横向重叠:

    // 初始化X轴并设置旋转
    CategoryAxis xAxis = new CategoryAxis();
    xAxis.setLabel("班级名称");
    xAxis.setTickLabelRotation(45); // 可根据需要调整旋转角度
    
    // 初始化Y轴(注意Y轴应为数值轴,不是类别轴)
    NumberAxis yAxis = new NumberAxis();
    yAxis.setLabel("平均缺勤次数");
    
    // 创建BarChart时关联轴
    BarChart<String, Double> income_data = new BarChart<>(xAxis, yAxis);
    
  • 调整图表宽度
    给BarChart设置足够的首选宽度,让标签有充足展示空间:

    income_data.setPrefWidth(800); // 根据类别数量和标签长度调整数值
    
  • 优化标签文本
    若类别名称过长,可对文本进行截断或换行处理:

    while (resultSet.next()) {
        String classeName = resultSet.getString(1);
        // 截断长文本
        if (classeName.length() > 10) {
            classeName = classeName.substring(0, 10) + "...";
        }
        // 或者换行显示
        // classeName = classeName.replaceAll("(.{5})", "$1\n");
        libelle_classe.add(classeName);
        numseance.add(resultSet.getDouble(2));
    }
    
  • 用ScrollPane包裹图表
    当类别数量较多时,将BarChart放入ScrollPane中,支持横向滚动查看所有标签:

    ScrollPane scrollPane = new ScrollPane(income_data);
    scrollPane.setFitToHeight(true); // 保持高度适配
    // 将scrollPane添加到界面容器中
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:05:20