[英]How can I get the width and the height of a JavaFX Label?
顯然有兩種方法getWidth
和getHeight
但是如果我們只是更改Label
文本值,它們將返回舊標簽大小。
例如,在此代碼中,背景大小沒有正確調整:
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
如下所示:
我看了一下這篇文章,但建議使用不推薦使用的方法:
返回“舊”大小的原因是,當您設置textProperty
時,該標簽實際上並沒有在GUI上更新,因此該大小不會更改。
您可以偵聽Label
的widthProperty和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-您可以檢查以下問題: FXML StackPane不能正確對齊子級
您可以通過兩種方式來實現。
方法1:將標簽的背景色設置為矩形。 因此,無論Label's
大小是多少,背景矩形都會相應地采用寬度。
label.setStyle("-fx-background-color:grey; -fx-padding:5");
方法2:根據您的標簽大小綁定矩形的大小
rectangle.prefWidthProperty(label.widthProperty());
rectangle.prefHeightProperty(label.heightProperty());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.