使用 Parent
来定义场景而不是 BorderPane
、Anchor
等是一个好的实践吗?
这样使用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);
}
}
最佳答案
这是一个很好的做法,因为 Parent
只是一个可以拥有子节点的 Node
(Parent
是 的子类)节点
)。
通过使用 Parent
而不是 BorderPane
,您可以使用更通用的类型,而不是将其绑定(bind)到特定类型的 Pane 。这样做的原因与将 ArrayList 声明为 List 类型的对象的原因相同。如果明天您要加载 VBox
,则无需修改代码。
关于java - JavaFX 中的 Parent 与 BorderPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35379407/