Indigo
Indigo

Reputation: 2997

Load Java FXML from sub package of start class

It must be a very simple thing to do perhaps but some how none of the solutions worked for me so far. So finally the question, maybe something that I didn't take in account.

I want to load FXML with its controller from sub package of the start class in Netbeans project. Tried all the solutions here referring to many different questions already, still didn't work.

The package structure:

Source Pacakge
    -a
        -b
            -c
                -d
                    StartUp_Classs.java
                    -ui
                        FXMLDocument.fxml
                        FXMLDocumentController.java

Here is the start method:

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

    try {
        setUserAgentStylesheet(STYLESHEET_MODENA);
        FXMLLoader loader = new FXMLLoader();
        Parent root = (Parent) loader.load(getClass().getResourceAsStream("/ui/FXMLDocument.fxml"));
        final FXMLDocumentController controller = (FXMLDocumentController) loader.getController();

        stage.addEventHandler(WindowEvent.WINDOW_SHOWN, controller::handleWindowShownEvent);
        stage.addEventHandler(WindowEvent.WINDOW_SHOWING, controller::handleWindowShowingEvent);

        Scene scene = new Scene(root);

        stage.setScene(scene);

        stage.setResizable(false);
        stage.toFront();
        stage.setTitle("Simple FXML");
        stage.getIcons().add(new Image(getClass().getResourceAsStream("/resources/images/Orange.jpg")));
        stage.show();
    } catch (IOException iOException) {
        iOException.printStackTrace();
    }
}

Any suggestions, would be a great help.

Upvotes: 1

Views: 850

Answers (2)

Indigo
Indigo

Reputation: 2997

In addition to ifLoop's correct answer above, just an additional hint if someone might face the same problem again.

If you refactor packages in Netbeans, it is not likely that Netbeans would update the Controller class path in FXML. So better go check correct class path in fx:controller= attribute at the beginning of FXML file and manually correct it.

In my case after refactoring packages:

It was like this:

fx:controller="OldPacakgeDefault.FXMLDocumentController"

It must have been this:

fx:controller="a.b.c.d.ui.FXMLDocumentController"

Upvotes: 1

ifloop
ifloop

Reputation: 8386

You might delete the leading / in your path String for the .fxml file.

Parent root = (Parent) loader.load(getClass().getResourceAsStream("ui/FXMLDocument.fxml"));

Upvotes: 1

Related Questions