如何创建具有正确宽度和高度的垂直标签?

How create a vertical label with correct width and height?

我需要可视化一些非常紧凑的数据。由于每个数据容器的高度有限,我决定将每个容器的标题移动到一边并垂直旋转。旋转标签时,它会保持其 parent 的尺寸。因此,标签的最大长度受限于 parent 的宽度。我怎样才能使标签的 maxWidth 是 parent 窗格的实际 maxHeight?

对于每个容器,我使用一个 GridPane。标签位于 StackPane 内,用于设置边框或更改背景颜色。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class Test extends Application {

  public void start(Stage primaryStage) throws Exception {
        // Part of the code

        GridPane gridPane = new GridPane();
        StackPane namePane;
        Label nameLabel;

        // ...

        // Header
        gridPane.getColumnConstraints().add(new ColumnConstraints(40.0));
        // Index
        gridPane.getColumnConstraints().add(new ColumnConstraints(50.0));
        // Name
        gridPane.getColumnConstraints().add(new ColumnConstraints(100.0,150.0,400));

        // int rows = ...; // Any integer between 1 and 6
        int rows = 5;

        for(int i = 0; i < rows; i++) {
            gridPane.getRowConstraints().add(new RowConstraints(30));
        }

        namePane = new StackPane();

        nameLabel = new Label("Name-123456789");
        nameLabel.setStyle("-fx-rotate: -90;");

        namePane.getChildren().add(nameLabel);
        gridPane.add(namePane,0,0,1,rows);

        // ...

        // Debug only
        gridPane.setGridLinesVisible(true);

        // just for running the example
        Scene scene = new  Scene(gridPane,700,700);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

下面两张图片代表了我希望标签的外观和实际外观。

我已经尝试将 Lable 的 maxWidth 更改为 Double.MAX_VALUE 但没有成功。

nameLabel.setMaxWidth(Double.MAX_VALUE);

StackPaneLabel 视为位置未被转换修改。这也会影响 StackPane.

的计算大小

要解决此问题,您可以将 Label 包装在 Parent 中,该 Parent 在计算其大小时会考虑转换:Group

namePane.getChildren().add(new Group(nameLabel));

注意: 如果 namePane 的高度变得太小而无法包含它,这不会调整 Label 的大小。要实现该效果,您需要实现自己的布局。