首页 > 解决方案 > 如何创建具有正确宽度和高度的垂直标签?

问题描述

我需要非常紧凑地可视化一些数据。由于每个数据容器的高度有限,我决定将每个容器的标题移到一边并垂直旋转。旋转标签时,它会保持其父级的尺寸。因此,标签的最大长度受父级宽度的限制。如何实现标签的 maxWidth 是父窗格的实际 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);

标签: javajavafxrotationlabel

解决方案


StackPaneLabel视为位置没有被变换修改。这也会影响StackPane.

要解决此问题,您可以将在计算其大小时考虑转换Label的 a包装起来:ParentGroup

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

注意:Label如果 的高度namePane变得太小而无法容纳它,这不会调整 的大小。为了达到这种效果,您需要实现自己的布局。


推荐阅读