如何在VBox中生长标签

2022-07-01 00:00:00 java javafx javafx-8

我得到了以下设置:

Label errorLabel = new Label("Hello Hans");
Label warningLabel = new Label("HEEELLLOOOOOOOOOOOOOOOOOOOOOOOOO");
VBox box = new VBox();
box.getChildren().addAll(errorLabel, warningLabel);
Tooltip t = new Tooltip();
t.setGraphic(box);
t.show();
我的问题是,warningLabelerrorLabel具有不同的大小。它们应该水平地长到相同的大小。我不想说具体的尺码。两个标签的大小必须为显示整个文本所需的大小。

问题是,这两个标签都有一个背景,您可以看到warningLabel占用了更多空间。我需要这些标签的两个背景都相等地增长。


解决方案

您可以将maxWidthProperty设置为Double.MAX_VALUE,同时设置为Label

Label errorLabel = new Label("Hello Hans");
errorLabel.setStyle("-fx-background-color: red");
Label warningLabel = new Label("HEEELLLOOOOOOOOOOOOOOOOOOOOOOOOO");
warningLabel.setStyle("-fx-background-color: orange");
warningLabel.setMaxWidth(Double.MAX_VALUE);
errorLabel.setMaxWidth(Double.MAX_VALUE);

输出Tooltip如下:

背景:Making Buttons the Same Size - Using a VBox - Example 2-1

将所有按钮的大小调整为VBox的宽度 窗格中,每个按钮的最大宽度设置为Double.MAX_VALUE 常量,使控件能够无限制地增长。一个 使用Maximum Value常量的替代方法是设置最大 将宽度设置为特定值,如80.0。

注意:重要信息:VBox的fillWidthProperty必须设置为true(该属性默认为true):

是否调整可调整大小的子项的大小以填充整个 VBox的宽度或保持其首选宽度并对齐 根据对齐hpos值。

这很重要,因为:

VBox将调整子项的大小(如果可调整大小)至其首选高度 并使用其填充宽度属性来确定是否调整其 宽度填充其自身的宽度或将其宽度保持为其首选的宽度 (填充宽度默认为True)。

因此,如果fillWidthProperty设置为True,VBox将尝试将其子项调整为自己的宽度,如果maxWidthProperty设置为每个子项的首选宽度,这是不可能的,这就是为什么必须将此属性设置为"足够大"的数字。

相关文章