JavaFX 在 ViewModel 上使用 Stage

标签 java mvvm javafx

我需要知道我的申请何时结束。我已经在启动 JavaFX 应用程序的 start 方法上实现了这个:

@Override
public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("/views/ClientWindow.fxml"));
    primaryStage.setTitle("ClientWindow");
    primaryStage.setScene(new Scene(root, 600, 400));

    primaryStage.setOnCloseRequest((event) -> {
        // Do my stuff with the service
        service.stopService();
    });
    primaryStage.show();
}

现在我需要将其更改为我的 ViewModel,因为我需要使用那里的 start 方法中定义的服务。所以我有两个选择:要么将服务对象传递给我的 ViewModel,要么在那里启动它。 我选择了第二个答案。

我的问题是:我如何知道我的窗口何时关闭? 这就是我在 ViewModel 中所做的:

    // Got a Label object and used it to get the scene and stage. (Ugh.)
    Stage stage = (Stage)this.labelStatus.getScene().getWindow();
    // Set the OnCloseRequest event handler to do what I did in the start() method.
    stage.setOnCloseRequest(event -> {
        // Stop services

    });

所以现在我想知道这样做是否是一个好主意,因为看起来我忽略了 MVVM 模型的想法。首先,我需要使用标签获取舞台(如果我的窗口上没有标签对象或者我实际上不必在 ViewModel 上使用它,会发生什么?)。

这是我应该走的路还是有更好的(阅读:更好,更直接的方式)来做到这一点?

编辑:显示定义 ModelView 的 FXML

查看fx:controller="viewmodels.ClientWindowViewModel"

<BorderPane minHeight="400.0" minWidth="600.0" xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1" fx:controller="viewmodels.ClientWindowViewModel">

最佳答案

如果您尝试遵循 MVVM 模式,那么您应该看看一个能够正确执行此操作的应用程序框架,例如mvvmFX。

https://github.com/sialcasa/mvvmFX

在您的设置中,您将 Controller 视为 View 模型,这是错误的。 Controller 属于 View ,有时也称为“代码隐藏”。 View 模型与 View 具有一对一的关系,但在其他方面独立于 View 。

如果您阅读 mvvmFX 教程,您还将学习如何在 View 和 View 模型之间进行通信,这有望回答您的问题。

关于JavaFX 在 ViewModel 上使用 Stage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35740823/

相关文章:

wpf - 如何在使用 PRISM 加载实际 Shell 之前显示初始屏幕和登录屏幕?

JavaFX:如何禁用 TableView 中的行?

java - 将 Maven 凭据存储在 settings.xml 之外

java - 即使在添加项目后列表大小为零

java - 如何根据输入长度更改 DecimalFormat 行为?

java - jBehave生成系统的 'live documentation'

wpf - 当 WPF ProgressBar 达到 100% 时,如何停止它的脉冲/动画?

.net - TreeView (MVVM) : Update Text Box from selected Item of tree

JavaFX 分页 : setPageCount(int) calls the page factory again but does not show the page

Javafx tableview 上的复选框取消选中,禁用同一行但不同列上的按钮