简体   繁体   English

如何获得JavaFX标签的宽度和高度?

[英]How can I get the width and the height of a JavaFX Label?

There are obviously the two methods getWidth and getHeight but they return the old label size if we just changed the Label text value. 显然有两种方法getWidthgetHeight但是如果我们只是更改Label文本值,它们将返回旧标签大小。

For example, in this code, the background is not correctly resized: 例如,在此代码中,背景大小没有正确调整:

Label speedLabel = new Label();
Rectangle backgroundLabel = new Rectangle();

// Some initialization

// Change the label text
speedLabel.setText(connection.getSpeed_bps()); // Sets a bigger number

// Adjust the background
backgroundLabel.setWidth(speedLabel.getWidth());
backgroundLabel.setHeight(speedLabel.getHeight());

After the initialization, my Label is like that: 初始化之后,我的Label是这样的:

在此处输入图片说明

And after the text change and the background adjustment, my Label is like that: 在更改文本和调整背景之后,我的Label如下所示:

在此处输入图片说明

I had a look at this post but it recommends a deprecated method: 我看了一下这篇文章,但建议使用不推荐使用的方法:

How to get label.getWidth() in javafx 如何在javafx中获取label.getWidth()

The reason for returning the "old" size that the label actually doesn't get updated on the GUI in the moment when you set the textProperty of it, therefore the size is not changed. 返回“旧”大小的原因是,当您设置textProperty时,该标签实际上并没有在GUI上更新,因此该大小不会更改。

You can listen to the widthProperty and heightProperty of the Label and resize the Rectangle in the listener: 您可以侦听LabelwidthPropertyheightProperty并在侦听器中调整Rectangle大小:

speedLabel.widthProperty().addListener((obs, oldVal, newVal) -> {
    backgroundLabel.setWidth(newVal.doubleValue());
});

speedLabel.heightProperty().addListener((obs, oldVal, newVal) -> {
    backgroundLabel.setHeight(newVal.doubleValue());
});

or simply use bindings between the properties: 或仅在属性之间使用绑定:

backgroundLabel.heightProperty().bind(speedLabel.heightProperty());
backgroundLabel.widthProperty().bind(speedLabel.widthProperty());

But if you just want to achieve a Label with some background, you don't actually need a Rectangle , just some CSS - you can check this question: FXML StackPane doesn't align children correctly 但是,如果您只想使用某些背景来实现Label ,则实际上并不需要Rectangle ,而只是需要一些CSS-您可以检查以下问题: FXML StackPane不能正确对齐子级

You can do it in two ways. 您可以通过两种方式来实现。

Approach 1: Give the background color of your label as that of rectangle. 方法1:将标签的背景色设置为矩形。 So that whatever is the Label's size, your background rectangle will take the width accordingly. 因此,无论Label's大小是多少,背景矩形都会相应地采用宽度。

label.setStyle("-fx-background-color:grey; -fx-padding:5");

Approach 2: Bind the Rectangle's size according to your label size 方法2:根据您的标签大小绑定矩形的大小

rectangle.prefWidthProperty(label.widthProperty());
rectangle.prefHeightProperty(label.heightProperty());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM