如何获得 JavaFX 标签的宽度和高度?
How can I get the width and the height of a JavaFX Label?
显然有 getWidth
和 getHeight
这两种方法,但如果我们只是更改 Label
文本值,它们 return 旧标签大小。
例如,在此代码中,背景未正确调整大小:
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());
初始化后,我的Label
是这样的:
然后文字改变和背景调整后,我的Label
是这样的:
我看过这个post,但它推荐了一种已弃用的方法:
How to get label.getWidth() in javafx
返回 "old" 大小的原因是当您设置它的 textProperty
时,标签实际上没有在 GUI 上更新,因此大小没有改变。
您可以收听 Label
的 widthProperty and heightProperty 并在收听器中调整 Rectangle
的大小:
speedLabel.widthProperty().addListener((obs, oldVal, newVal) -> {
backgroundLabel.setWidth(newVal.doubleValue());
});
speedLabel.heightProperty().addListener((obs, oldVal, newVal) -> {
backgroundLabel.setHeight(newVal.doubleValue());
});
或者简单地使用属性之间的绑定:
backgroundLabel.heightProperty().bind(speedLabel.heightProperty());
backgroundLabel.widthProperty().bind(speedLabel.widthProperty());
但是如果你只是想通过一些背景获得 Label
,你实际上并不需要 Rectangle
,只需要一些 CSS - 你可以检查这个问题:
您可以通过两种方式完成。
方法一:
将标签的背景颜色设置为矩形。因此,无论 Label's
大小是多少,您的背景矩形都会相应地采用宽度。
label.setStyle("-fx-background-color:grey; -fx-padding:5");
方法二:
根据你的标签大小绑定矩形的大小
rectangle.prefWidthProperty(label.widthProperty());
rectangle.prefHeightProperty(label.heightProperty());
显然有 getWidth
和 getHeight
这两种方法,但如果我们只是更改 Label
文本值,它们 return 旧标签大小。
例如,在此代码中,背景未正确调整大小:
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());
初始化后,我的Label
是这样的:
然后文字改变和背景调整后,我的Label
是这样的:
我看过这个post,但它推荐了一种已弃用的方法:
How to get label.getWidth() in javafx
返回 "old" 大小的原因是当您设置它的 textProperty
时,标签实际上没有在 GUI 上更新,因此大小没有改变。
您可以收听 Label
的 widthProperty and heightProperty 并在收听器中调整 Rectangle
的大小:
speedLabel.widthProperty().addListener((obs, oldVal, newVal) -> {
backgroundLabel.setWidth(newVal.doubleValue());
});
speedLabel.heightProperty().addListener((obs, oldVal, newVal) -> {
backgroundLabel.setHeight(newVal.doubleValue());
});
或者简单地使用属性之间的绑定:
backgroundLabel.heightProperty().bind(speedLabel.heightProperty());
backgroundLabel.widthProperty().bind(speedLabel.widthProperty());
但是如果你只是想通过一些背景获得 Label
,你实际上并不需要 Rectangle
,只需要一些 CSS - 你可以检查这个问题:
您可以通过两种方式完成。
方法一:
将标签的背景颜色设置为矩形。因此,无论 Label's
大小是多少,您的背景矩形都会相应地采用宽度。
label.setStyle("-fx-background-color:grey; -fx-padding:5");
方法二: 根据你的标签大小绑定矩形的大小
rectangle.prefWidthProperty(label.widthProperty());
rectangle.prefHeightProperty(label.heightProperty());