【问题标题】:Switching scenes in JavaFX with ActionEvent使用 ActionEvent 在 JavaFX 中切换场景
【发布时间】:2023-03-31 12:30:01
【问题描述】:

您好,我有一个带有几个控制器的 JavaFX 应用程序,我有 2 个选项可以返回到上一个屏幕。用户可以单击“离开”按钮,或者在完成此屏幕上的某些任务后将自动移至上一个。我在这里有问题,因为我创建了方法 wiut fxml 注释,该方法将 ActionEvent 对象作为参数,并在用户单击按钮和用户完成任务时调用,并且应该自动移动到上一个屏幕我无法调用此方法,因为我没有这个对象, 它是在执行操作时创建的 - 在这种情况下单击。我怎样才能使这两个“退出”选项成为可能?

所以这是我的方法,我的按钮使用了“onAction”:

@FXML
    private void leaveRoomAction(ActionEvent event) {
        try {
            removePlayerFromRoom();

            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("LobbyView.fxml"));
            Parent root = (Parent) loader.load();

            LobbyController lobbyController = (LobbyController)loader.getController();
            lobbyController.setClientThread(client);
            lobbyController.setNameAndBalance(client.getPlayer().getName());

            Scene scene = new Scene(root);
            Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

稍后在程序的其他部分:

if(isFinished()){
//here I want write leaving this screen and getting back to previous
}

【问题讨论】:

标签: javafx scene stage


【解决方案1】:

首先,找到另一种方法来获取对Stage 的引用。由于您几乎可以肯定在控制器中引用了场景中的某个节点,因此您可以替换

Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();

Stage stage = (Stage) anyNode.getScene().getWindow();

anyNode 只是你注入控制器的东西。

现在您根本不需要该参数,因此您可以将其删除。 IE。你最终得到了

@FXML
private Node anyNode ; // probably a more specific type than Node.

@FXML
private void leaveRoomAction() {
    try {
        removePlayerFromRoom();

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("LobbyView.fxml"));
        Parent root = (Parent) loader.load();

        LobbyController lobbyController = (LobbyController)loader.getController();
        lobbyController.setClientThread(client);
        lobbyController.setNameAndBalance(client.getPlayer().getName());

        Scene scene = new Scene(root);
        Stage stage = anyNode.getScene().getWindow();
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

现在你可以调用方法了:

if ( isFinished() ) {
    leaveRoomAction()
}

【讨论】:

    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 2016-09-09
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    相关资源
    最近更新 更多