简体   繁体   中英

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.

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:

在此处输入图片说明

And after the text change and the background adjustment, my Label is like that:

在此处输入图片说明

I had a look at this post but it recommends a deprecated method:

How to get label.getWidth() in javafx

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.

You can listen to the widthProperty and heightProperty of the Label and resize the Rectangle in the listener:

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

You can do it in two ways.

Approach 1: Give the background color of your label as that of rectangle. So that whatever is the Label's size, your background rectangle will take the width accordingly.

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

Approach 2: Bind the Rectangle's size according to your label size

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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