简体   繁体   中英

Switching between Scenes in Java fx with fxml files and an Controller

In this programm i wanna switch between scenes by button click.I get an Exception on the line where i want to set the Location of the FXML Loader. In other Tutorials or posts i see it is done in the same way i did it.I also checked the Path to the fxml file a hundred times.

So the special case is to switch from QuestionTableViewController with the fxml of tableViewQuestion.fxml to the tableViewUser.fxml with the Controller UserTableViewController. At least i start the Programm in MyApplication.

Could that Exception arrive, because my Class is implementimg initializable? And if yes why and how to fix this? Or maybe because i have different Controllers for the fxml-files? but why and how could i fix this?

So now i ask you, where is my dumb fault at that Programm?

Controller with the switchMethod:

public class QuestionTableViewController implements Initializable{
    @FXML
        TableView<Question> questionTable;
    public void changeToUserDatabase() throws IOException {
         Scene quizScene = new Scene(FXMLLoader.load(getClass().
                           getResource("src/view/tableViewUser.fxml")));
        Stage primaryStage = (Stage) questionTable.getScene().getWindow();
        primaryStage.setScene(quizScene);
        primaryStage.show();
    }}

Start Method:

public class MyApplication extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("view/tableViewQuestion.fxml"));
        primaryStage.setTitle("Database of Century");
        primaryStage.setScene(new Scene(root, 750, 500));
        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

在这里您可以看到我的程序的结构

PS: I just show the methods i think are needed, of course i had a button with the onMouseClick method and a content for my tableView. If you think they could be relevant please commit and i will add it in the question. :)

The problem is that you are trying to access the resource in the wrong place. Based on what I read in this question , you should go up one directory to access the fxml file correctly. Try this:

    Parent root = FXMLLoader.load(getClass().getResource("../view/tableViewQuestion.fxml"));

Where .. should indicate looking at the parent directory.

EDIT:

The above will not work inside a packaged jar. To easily overcome your issue, create a class in the views package and use it to load resources.

For example create class ViewLoader in src/view and load your fxml files as follows:

    Parent root = FXMLLoader.load(ViewLoader.class.getResource("tableViewQuestion.fxml"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM