gpt4 book ai didi

java - 加载FXML的两种方式;为什么一个比另一个更受欢迎?

转载 作者:行者123 更新时间:2023-11-29 07:26:30 24 4
gpt4 key购买 nike

我正在寻找关于为什么我们应该在加载和显示新的 FXML 阶段时使用一种方法而不是另一种方法的反馈。

大多数时候,我看到的教程之类的展示了从一个单独的类完成的阶段加载。但是,它也可以在 FXML 文件的 Controller 本身内完成,我个人认为这种方式更简洁、更易于管理。

考虑以下 Main.java 类:

public class Main extends Application {

@Override
public void start(Stage stage) throws Exception {

// Method 1:
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout.fxml"));
loader.setController(new LayoutController());

stage.setScene(new Scene(loader.load()));
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}

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

这似乎是流行的方法。它创建 Controller 并设置 Scene 然后显示它。

但是,如果我们将 start() 方法改为:

@Override
public void start(Stage stage) throws Exception {

LayoutController controller = new LayoutController();
controller.showStage();

}

并将 FXML 加载代码移动到 LayoutController 构造函数中,结果是一样的:

public class LayoutController {

@FXML
private Label label;

private Stage stage = new Stage();

public LayoutController() {

// Method 2:
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout.fxml"));
loader.setController(this);

stage.setScene(new Scene(loader.load()));
} catch (IOException e) {
e.printStackTrace();
}
}

public void showStage() {
this.stage.showAndWait();
}
}

我在这里看到的好处是 View 和逻辑之间的更多分离。关于 LayoutController 及其关联的 FXML 文件的所有内容都包含在一个地方。

所以我的问题是:第二种方法有什么问题?我假设这不是标准方法是有原因的,但我看不出有任何缺点。

Would a question like this be more suited to Code Review? I'm not really asking for opinions, as there seems to be a general "rule" that the first method be used.

最佳答案

在这种情况下没有太大区别。

对于较大的程序,第二种方法不受欢迎:

它违反了single responsibility principle :

该类负责:

  • 创建场景
  • 搭建舞台
  • 显示舞台(更糟糕的是,它以可能干扰其他逻辑的方式执行此操作 (showAndWait))
  • 它是 View 的 Controller ,可能会负责处理多个事件

此外,该类的设计方式可以防止责任毫无问题地转移到其他类。

在较大的程序中,您可能希望创建一个类来管理向 View 传递数据、排列窗口或将 View 显示为场景的一部分等。第二种方法不适合这种情况。

此外,不重复自己也变得更加困难。除非将逻辑移至通用父类(super class)型,否则还需要在每个 Controller 类中实现显示场景的逻辑。重复相同或相似的代码会导致代码难以维护。


注意:使用单个类来加载 fxml 并用作 Controller 不一定是坏事,但您应该使用 Custom Component 中介绍的方法Introduction to FXML.

关于java - 加载FXML的两种方式;为什么一个比另一个更受欢迎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51618510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com