简体   繁体   中英

Parent vs BorderPane in JavaFX

Is it a good praxis to use Parent to define scene instead of BorderPane , Anchor etc?

What are the advantages of using Parent in this way?

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 ).

By using Parent instead of BorderPane , you're using a more general type, instead of tying it to a certain type of pane. You do this for the same reason as you would declare an ArrayList as a an object of type List. If tomorrow you're loading a VBox , you don't need to modify your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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