gpt4 book ai didi

java - 带有 JavaFX 和 FXML 的 MVC

转载 作者:行者123 更新时间:2023-11-29 04:37:44 30 4
gpt4 key购买 nike

如果我有一个使用 FXML 的 JavaFX 项目,我应该如何构建它以遵循模型- View - Controller 模式?这就是我假设的一般结构:

模型 - 底层程序(GUI 代表什么)。
查看 - FXML 文件。
Controller - FXML Controller 。

此表示的问题是无法通知 View 模型的更改,因为它只是一个 FXML 文件。 View 应该是 FXML Controller 类,然后我应该有一个主 Controller 类,以便 FXML Controller 从模型中获取信息,而主 Controller 处理 Action 事件吗?在这种情况下,主 Controller 将如何访问 JavaFX 节点?

此外,在 MVC 模式中,主要方法应该在哪里?现在,它在我的 JavaFX Application 类中,然后它对程序的其余部分不执行任何操作。另外,JavaFX Application 类应该是 MVC 模式的一部分,还是只需要初始化 GUI?

问题摘要(请阅读完整帖子):

  1. 如何构建使用 FXML 的 JavaFX 项目以遵循 MVC 模式? View 应该是 FXML Controller 类,然后我应该有一个主 Controller 类,以便 FXML Controller 从模型获取信息,而主 Controller 处理 Action 事件吗?
  2. 在 MVC 模式中,main 方法应该在哪里?
  3. JavaFX Application 类应该是 MVC 模式的一部分,还是只需要初始化 GUI?

最佳答案

How do I structure my JavaFX project which uses FXML to adhere to the MVC pattern? Should the view be the FXML controller class, and then should I have a main controller class such that the FXML controller gets information from the model, and the main controller handles the action events?

JavaFX 和 Swing 都在插入 View 和 Controller 之间的紧密耦合,理由是制作通用的 Controller 很困难。但是,MVC 本身有一些解释,所以有点模糊。

鉴于 View 和 Controller 紧密耦合的理由,您有一些选择。我建议两个,也许其他人可以添加甚至不同意。

1) 接受 View 类只是一个虚拟对象,用于加载 FXML 文件、设置 SceneStage 以及制作 FXMLController 类观察模型并更新 View 。

这将 Controller 限制为 JavaFXML 应用程序,这意味着它不能轻松地与 Swing 等实例互换。尽管更改 View 既快速又简单,只要它引用正确的 Controller 并且所有 onAction 或等效的 Node 属性都使用相同的引用。

2) 不要使用提供的骨架代码。相反,让 View 加载 FXML 文件并手动访问节点,另外从 FXML 文件中删除 fx:controller 属性,并从 FXML 文件中的相关节点中删除 onAction 属性。

然后您可以根据需要从 View 中的 FXML 访问任何节点,例如

Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Button example = (Button) root.lookup("#button"); // #button exists in FXMLDocument.fxml
example.setOnAction(e -> { myController.doSomething(); });

这为您提供了优势或指定您自己的通用 Controller ,并允许 View 类观察模型本身。

归根结底,最重要的是将模型与 View 和 Controller 分开,因为模型是程序的核心。 Smart Model, Thin Controller, Dumb View

Where should the main method be?

没关系。但是,如果创建的 JAR 是由 JavaFX Packager Tool 完成的,则 JavaFX 应用程序并不严格需要 main 方法,而是使用 launch作为切入点。但是,您可以使用 main 方法作为单独类中的入口点并调用 Application.launch(MyJavaFXApplicationClass.class);相反。

Should the JavaFX Application class be part of the MVC pattern, or is it only necessary to initialize the GUI?

是的,因为它是 View 的一部分。看我上面提到的两种方法。

关于java - 带有 JavaFX 和 FXML 的 MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557492/

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