2

I'm having trouble when trying to switch from a scene to another scene. The scenario is this:

Current View and Controller: login.fxml and LoginController

Next step View and Controller: loggedWindow.fxml and UserPanelController.


Now, I'm in LoginController and trying to switch the scene to loggedWindow.fxml sending to UserPanelController a parameter, but when I'm using my code I get:

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

LoginController:

FXMLLoader loggedWindow = null;
loggedWindow = FXMLLoader.load(getClass().getResource("loggedWindow.fxml")); // here crashes!
Pane root = loggedWindow.load();

UserPanelController controller = loggedWindow.getController();
controller.initData(customer);

Stage switchScene = (Stage)((Node)event.getSource()).getScene().getWindow();
switchScene.setResizable(false);
switchScene.setTitle("Welcome " + customer.FirstName + " " + customer.LastName);
switchScene.setScene(new Scene(root, 800, 500));

switchScene.show();

LoggedWindow.fxml

<Pane maxHeight="500.0" maxWidth="800.0" minHeight="500.0" minWidth="800.0" prefHeight="500.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Main.UserPanelController">
   <children>
      <ToolBar prefHeight="40.0" prefWidth="831.0">
        <items>
         .
         .
         stuff (buttons/labels and so on).
         .
         .
</Pane>

I would appreciate any help! Thanks in advance.

Update 1

Also took in consideration this reference: Accessing FXML controller class

Community
  • 1
  • 1
Shmwel
  • 1,697
  • 5
  • 26
  • 43
  • Create first an instance: `FXMLLoader loggedWindow = new FXMLLoader(getClass()...);`, and then you can load the fxml file `Pane root = loggedWindow.load();` – José Pereda Dec 18 '14 at 22:14

1 Answers1

7

You're using the "load" method of FXMLLoader which returns the root node of your .fxml file. In that case, it's returning your Pane.

You should use it to create your scene!

See the example given in the JavaFX tutorial, like:

Pane root = FXMLLoader.load(getClass().getResource("loggedWindow.fxml"));
Scene scene = new Scene(root, width, height, color);

Other way, taken from one of my old code, using non-static FXMLLoader:

FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlFile));
Parent root;

try {
    root = loader.load();
} catch (IOException ioe) {
    // log exception
    return;
}

// Color.TRANSPARENT allows use of rgba colors (alpha layer)
setScene(new Scene(root, Color.TRANSPARENT));
Reinstate Monica
  • 2,767
  • 3
  • 31
  • 40
VinceOPS
  • 2,602
  • 18
  • 21
  • Well sounds interesting. But, I wonder if I can use `getController()` method inside of type `Pane`, because I tried and doesn't work.. :-? – Shmwel Dec 19 '14 at 07:23
  • If you want the controller,you need to call getController() of an FXMLLoader instance. In that case, loader.getController() if we look at my second example. – VinceOPS Dec 19 '14 at 08:08