简体   繁体   English

JavaFX中的Parent与BorderPane

[英]Parent vs BorderPane in JavaFX

Is it a good praxis to use Parent to define scene instead of BorderPane , Anchor etc? 使用Parent来定义场景而不是BorderPaneAnchor等是一个很好的实践吗?

What are the advantages of using Parent in this way? 以这种方式使用Parent的好处是什么?

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("Main.fxml")); //Insted of this:   BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("Main.fxml"));
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

It is good practice, because a Parent is merely a Node that can have child nodes ( Parent is a subclass of Node ). 这是很好的做法,因为Parent只是一个Node ,可以有子节点( Parent是子类Node )。

By using Parent instead of BorderPane , you're using a more general type, instead of tying it to a certain type of pane. 通过使用Parent而不是BorderPane ,您使用的是更通用的类型,而不是将其绑定到某种类型的窗格。 You do this for the same reason as you would declare an ArrayList as a an object of type List. 这样做的原因与将ArrayList声明为List类型的对象的原因相同。 If tomorrow you're loading a VBox , you don't need to modify your code. 如果明天要加载VBox ,则无需修改代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM