Jeankowkow
Jeankowkow

Reputation: 834

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:

enter image description here

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

enter image description here

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

How to get label.getWidth() in javafx

Upvotes: 2

Views: 5214

Answers (2)

DVarga
DVarga

Reputation: 21799

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

Upvotes: 4

Harshita Sethi
Harshita Sethi

Reputation: 2125

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());

Upvotes: 1

Related Questions