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

JavaFX旋转Text元素后Bounding Box未适配的布局问题

解决JavaFX旋转Text后Bounding Box未适配的问题

在构建Y坐标轴时,通过旋转JavaFX的Text实现垂直轴标签,但旋转后Text的bounding box未随旋转调整,导致外层容器水平宽度过大,轴标签与刻度间产生不必要的间隙,且不能使用平移技巧(避免遮挡和交互问题)。

核心原因

JavaFX的Region类容器(如VBox)在计算自身布局尺寸时,使用的是子节点未应用变换的本地边界(boundsInLocal),而非变换后的实际显示边界(boundsInParent)。因此旋转Text后,外层容器仍会按照原文本的水平宽度来布局,造成冗余空间。

解决方案

使用Group包裹旋转后的Text元素。Group是一个非布局容器,它的布局边界会自动适配子节点应用变换后的实际显示边界,这样外层的VBox就能根据旋转后的文本宽度来调整自身尺寸,消除冗余间隙。

修改后的代码

public class SimpleYAxis extends HBox {

    public SimpleYAxis(double[] tickValues, String axisLabelText, double tickLength, double rowHeight) {

        this.setAlignment(Pos.CENTER);
        this.setSnapToPixel(true);

        VBox labelContainer = new VBox();
        labelContainer.setAlignment(Pos.CENTER);
        labelContainer.setStyle("-fx-border-color: lime");
        
        // 关键修改:用Group包裹旋转后的Text
        Text axisLabel = new Text(axisLabelText);
        axisLabel.setTextAlignment(TextAlignment.CENTER);
        axisLabel.setTextOrigin(VPos.CENTER);
        axisLabel.setStyle("-fx-font: 18 helvetica;");
        axisLabel.setRotate(270);
        Group labelGroup = new Group(axisLabel); // 添加Group包裹
        labelContainer.getChildren().add(labelGroup); // 将Group加入容器
        
        this.getChildren().add(labelContainer);

        GridPane axisPane = new GridPane();

        for (int yIdx = 0; yIdx < tickValues.length; yIdx++) {
            Text tickLabel = new Text(String.format("%.2f", tickValues[yIdx]));
            tickLabel.setTextAlignment(TextAlignment.CENTER);
            tickLabel.setTextOrigin(VPos.TOP);
            axisPane.add(tickLabel, 0, yIdx);
            Line tick = new Line(0, tickLength, 10, tickLength);
            axisPane.add(tick, 1, yIdx);
            axisPane.getRowConstraints().add(new RowConstraints(rowHeight));
        }

        ColumnConstraints axisColConstr = new ColumnConstraints();
        axisColConstr.setFillWidth(false);
        axisColConstr.setHalignment(HPos.RIGHT);

        axisPane.getColumnConstraints().add(axisColConstr);

        Line yAxis = new Line(0, 0, 0, rowHeight * (tickValues.length - 1));
        yAxis.setTranslateY(yAxis.getBoundsInLocal().getHeight() / 2);
        yAxis.setTranslateX(5);
        axisPane.add(yAxis, 1, 0);

        this.getChildren().add(axisPane);

    }

}

说明

  • Group会根据子节点的变换(旋转、缩放等)重新计算自身的布局边界,外层的VBox会以此为依据调整尺寸,完美适配垂直文本的宽度。
  • 该方案无需使用平移操作,不会影响其他布局元素的交互和显示,完全通过布局容器的特性解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:32:40