[英]Binding label to bottom-center of scene - JavaFX
我試圖弄清楚如何在場景底部完美地居中和綁定標簽。 我在這里有一個簡單的測試應用程序來顯示我正在使用什么以及我的問題是什么。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class LabelTest extends Application {
@Override
public void start(Stage stage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 400, 400);
Label label = new Label("Testing testing 1 2 3");
label.layoutXProperty().bind(scene.widthProperty().divide(2).subtract(label.getWidth() / 2)); //Should align label to horizontal center, but it is off
label.layoutYProperty().bind(scene.heightProperty().subtract(label.getHeight() + 35)); //Aligns the label to bottom of scene
root.getChildren().add(label);
stage.setScene(scene);
stage.show();
}
}
我的定位背后的邏輯對我來說很有意義,所以我不確定為什么它不是水平居中的。 我在下面包含了一個屏幕截圖來顯示輸出的樣子:
下面是更多我想要它的樣子(還有一點,但你明白了)
在此先感謝任何幫助我的人!
讓布局管理器為您做布局:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LabelTest extends Application {
@Override
public void start(Stage stage) throws Exception {
Label label = new Label("Testing testing 1 2 3");
BorderPane root = new BorderPane();
//center label by
//BorderPane.setAlignment(label, Pos.CENTER);
//root.setBottom(label);
//OR
root.setBottom(new StackPane(label));
Scene scene = new Scene(root, 400, 400);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
問題是您在綁定時采用寬度/高度的值。 在這種情況下,它將為 0,因為它們尚未呈現。 您還需要綁定這些屬性進行計算。
label.layoutXProperty().bind(scene.widthProperty().divide(2).subtract(label.widthProperty().divide(2)));
label.layoutYProperty().bind(scene.heightProperty().subtract(label.heightProperty().add(35)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.