Opening a new scene in java FX


Question

I have two FXML files and one Controller.

I have posted the code in which i have tried to create a second stage (and failed).

Error message is:

javafx.scene.layout.AnchorPane cannot be cast to javafx.fxml.FXMLLoader 

How do I fix it?

@FXML private Scene trial_scene;
@FXML public  Stage m;     

@FXML public void click(Stage stage) throws IOException {
    m = new Stage();
    openWindow(); 
}

@FXML private void openWindow() throws IOException {
    FXMLLoader root =FXMLLoader.load(
        SampleController.class.getResource(
            "settings.fxml"
        )
    );
    m.initModality(Modality.WINDOW_MODAL);
    m.setTitle("My modal window");
    m.setScene(trial_scene);
    m.show();
}
1
0
1/18/2014 9:54:20 AM

Accepted Answer

The static method FXMLLoader.load returns the root node (and so the objet hierarchy) defined in the .fxml file. In your case it seems to be an AnchorPane.

Your fist line should be

AnchorPane root = FXMLLoader.load(SampleController.class.getResource("settings.fxml"));

Use this object to construct your new scene, for example

Scene trial_scene = new Scene(root, 300, 300, Color.BLACK);

Then pass this scene to your new stage

m.setScene(trial_scene); 
1
1/18/2014 10:06:29 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon