meh_programmer meh_programmer - 18 days ago 5
Java Question

JavaFX Issue with Switching Scene

I have a

Utility
class in which I am trying to create a
static
method called
switchScene
to be able to easily switch scenes in my stage. This is the code I tried to use:

public class Utility {
public static void switchScene(String path) {
Stage stage = getMainStage(); // Assume this returns the primary stage
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource(path));

try {
Parent root = loader.load();
Controller controller = loader.getController();
controller.start();
Scene scene = new Scene(root);
stage.setScene(scene);
} catch (IOException e) {
e.printStackTrace();
}
}
}


I thought this code would work (I'm making every controller for my view implement the
Controller
interface which just has a
start
method on it.), however I get this error message:

java: non-static method getClass() cannot be referenced from a static context


Is there something I can do to work around this?

Answer

Don't get path as a String. Change it to URL

public class Utility {
        public static void switchScene(URL path) {
            Stage stage = getMainStage(); // Assume this returns the primary stage
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(path);

            try {
                Parent root = loader.load();
                Controller controller = loader.getController();
                controller.start();
                Scene scene = new Scene(root);
                stage.setScene(scene);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Now every one can call it with their own fxml wherever it may be and the signature is less confusing about what the argument is supposed to be:

Utility.switchScene(SomeClass.class.getResource("someView.fxml"));

It's irrelevant to your question but I also suggest that you get the Stage as an argument or via dependency injection rather than calling a function (Inversion of Control principle) and throw IOException rather than catching it, as it informs users of utility class about possible ways things can go wrong. I also think it's not a bad idea to return the Controller rather than returning void so that it can be used by users.