JavaFX如何在运行时获取BorderPane高度?

时间:2014-12-09 13:17:24

标签: javafx

在我的程序中,我创建了不同的BorderPanes。如何在运行时获得(不同的)高度?当我使用borderPane.getHeight()borderPane.getPrefHeight()时,它始终返回-1.0或0.0。 谢谢! 代码示例:

public class JavaFXApplication8 extends Application {

@Override
public void start(Stage primaryStage) {
    Button btn1 = new Button("1");
    Button btn2 = new Button("2");
    Button btn3 = new Button("3");     
    BorderPane borderPane = new BorderPane();
    StackPane root = new StackPane();   
    borderPane.setCenter(btn1);
    borderPane.setBottom(btn2);
    borderPane.setTop(btn3);
    System.out.println("borderPane's height: "  + borderPane.getHeight()); //Print 0.0
    root.getChildren().add(borderPane);
    Scene scene = new Scene(root, 300, 250);       
    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}   

}

1 个答案:

答案 0 :(得分:0)

borderPane.getHeight()将打印0,因为当你获得高度时它仍未显示。

有几种选择。最简单的方法是使用PlarForm.runLater()

包围您的代码
Platform.runLater(new Runnable() {

            @Override
            public void run() {
                System.out.println("borderPane's height: " + borderPane.getHeight());
            }
        });