简体   繁体   中英

How to set the fxml loader's location to an fxml in another package

I am trying to make an app that has a dialog for making a new item. I had already programmed it but wanted to clean up the file structure, so I moved the fxml for the dialog and its controller to their own package. The files for the dialog are in a package called newItemDialog. When I try to launch it I get an java.lang.IllegalStateException: Location is not set error. I have already tried the solution at how to locate fxml from another package?

Here is a picture of my project's file structure: Project File Structure

Here is the code to launch the dialog

@FXML
public void showNewItemDialog() {
    Debug.getInstance().log("Entering showNewItemDialog method", false);
    Dialog<ButtonType> dialog = new Dialog<>();
    dialog.initOwner(mainBorderPane.getScene().getWindow());
    dialog.setTitle("Create new item");
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("/newItemDialog/newToDoItem.fxml"));
    try {
        dialog.getDialogPane().setContent(fxmlLoader.load());
    } catch(IOException e) {
        Debug.getInstance().log("An error has occurred in the showNewItemDialog method\n", true);
        e.printStackTrace();
        return;
    }

    dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
    dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);

    Optional<ButtonType> result = dialog.showAndWait();
    if(result.isPresent() && result.get() == ButtonType.OK) {
        Debug.getInstance().log("Updating ListView", false);
        NewItemDialogController controller = fxmlLoader.getController();
        ToDoItem newItem = controller.processResults();
        toDoListView.getSelectionModel().select(newItem);
    }
}

Thanks!

In most of these cases, the path to the .fxml file is not correctly set. You can try setting the correct path for example by:

1. using the absolut path:

FXMLLoader loader = new  XMLLoader(getClass().getResource("/com/vincent/todo/newItemDialog/newToDoItem.fxml"));

2. using the relative path:

FXMLLoader loader = new  XMLLoader(getClass().getResource("newItemDialog/newToDoItem.fxml"));

3. using a class that is in the same package:

FXMLLoader loader = new  XMLLoader(NewItemDialogController.class.getResource("newToDoItem.fxml"));

您应使用getClass().getResource("newItemDialog/newToDoItem.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