Java 应用程序中通过调用方法从控制器切换场景

Java 应用程序中通过调用方法从控制器切换场景,java,javafx,fxml,Java,Javafx,Fxml,我正在做一个项目,我必须根据用户输入切换场景。目前,我有一个Gui类,它是一个应用程序,加载第一个fxml文件,它由MainController类启动: public class MainController { public MainController() { Application.launch(Gui.class); } } Gui类: public class Gui extends Application{ Stage primaryStage; //I wan

我正在做一个项目,我必须根据用户输入切换场景。目前,我有一个Gui类,它是一个应用程序,加载第一个fxml文件,它由MainController类启动:

public class MainController {


public MainController() {
    Application.launch(Gui.class);
}

}
Gui类:

public class Gui extends Application{

Stage primaryStage;


//I wanna ideally use this method to switch scenes
public void switchen(String nextScene) throws Exception
{
    Parent nextS;
    if(nextScene.equals("singleMenue"))
    {
        nextS = FXMLLoader.load(getClass().getResource("SingleMenue.fxml"));
        primaryStage.hide();
        primaryStage.setScene(new Scene(nextS, 900, 600));
        primaryStage.show()
    }

}


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

    this.primaryStage = primaryStage;
    Parent decisionScene = FXMLLoader.load(getClass().getResource("Decision.fxml"));
    primaryStage.setTitle("title");
    primaryStage.setScene(new Scene(decisionScene, 900, 600));
    primaryStage.show();

    }
我还为每个.fxml文件提供了不同的控制器类(这是第一个):

那么我现在如何从控制器内部切换场景呢

我尝试使用MVC模式,但我不知道DecisionController对象如何在Gui应用程序中调用方法。我需要进入一个正在运行的线程中,对吗? 我也不知道如何将Gui实例交给DecisionController,因为后者是从Decision.fxml初始化的

我尝试的另一件事是直接从DecisionController切换场景:

@FXML
private void buttonPressed(ActionEvent event) throws IOException
{

    if(event.getSource() == singleButton)
    {
        System.out.println("single");

        Stage mainstage = (Stage) singleButton.getScene().getWindow();
        Parent singleScene = FXMLLoader.load(getClass().getResource("SingleMenue.fxml"));
        mainstage.setScene(new Scene(singleScene, 900, 600));

    }
    else if(event.getSource() == multiButton)
    {
        System.out.println("multi");
    }

}

这是可以理解的,因为不可能从应用程序线程外部进行操作


我对JavaFX&FXML有点陌生,所以我对程序结构的总体想法可能完全错误,也许这不是MVC的方式。任何反馈都非常感谢:)

“这也不能理解,因为从应用程序线程外部进行操作是不可能的。”但这是在FX应用程序线程上调用的。它在什么意义上不起作用?“发生了什么事?”詹姆斯说,它给了我一个错误。由于已经确信它不应该工作,我将其归因于我的“从应用程序线程外部进行操作”的想法。看到您的评论后,我再次查看了代码,并意识到它给了我一个错误,因为我的控制器与我的.fxml文件位于不同的包中,因此我必须以不同于Gui的方式加载它。我想这是一个提醒,要真正公正地看待错误消息。以及线程如何工作。无论如何,非常感谢您的快速响应和帮助解决问题:)
@FXML
private void buttonPressed(ActionEvent event) throws IOException
{

    if(event.getSource() == singleButton)
    {
        System.out.println("single");

        Stage mainstage = (Stage) singleButton.getScene().getWindow();
        Parent singleScene = FXMLLoader.load(getClass().getResource("SingleMenue.fxml"));
        mainstage.setScene(new Scene(singleScene, 900, 600));

    }
    else if(event.getSource() == multiButton)
    {
        System.out.println("multi");
    }

}