JavaFX场景切换静态方法中getClass()调用报错,求解决方案
Ah, I see the issue here! The problem is that you're trying to call getClass() inside a static method—and that's a no-go because getClass() is an instance method, meaning it belongs to an object of your class, not the class itself. Static methods don't have access to instance context, so the compiler throws an error when you try to use it here.
Let's break down the fixes with actionable solutions:
Solution 1: Use your class name directly instead of getClass()
Since static methods are tied to the class, you can reference the class explicitly. Replace getClass() with your actual class name followed by .class (e.g., SceneNavigator.class if your class is named SceneNavigator). This works because ClassName.class is a statically accessible reference to your class's metadata.
Here's the modified code (with a cleaner FXMLLoader usage too—no need for manual openStream()):
public static void callNewScene(String sceneJump, Event event) throws IOException { ((Node)event.getSource()).getScene().getWindow().hide(); Stage primaryStage = new Stage(); // Replace YourClassName with the actual name of your class containing this method FXMLLoader loader = new FXMLLoader(YourClassName.class.getResource(sceneJump)); Pane root = loader.load(); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); }
Solution 2: Pass a Class<?> parameter for flexibility
If you want to reuse this method across multiple classes, add a Class<?> parameter. Callers can pass getClass() from their instance context, or ClassName.class statically.
Modified method:
public static void callNewScene(String sceneJump, Event event, Class<?> clazz) throws IOException { ((Node)event.getSource()).getScene().getWindow().hide(); Stage primaryStage = new Stage(); FXMLLoader loader = new FXMLLoader(clazz.getResource(sceneJump)); Pane root = loader.load(); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); }
Call it from an instance method:
callNewScene("/views/MyNewScene.fxml", event, getClass());
Or from a static context:
callNewScene("/views/MyNewScene.fxml", event, SomeOtherClass.class);
Solution 3: Convert the method to an instance method
If your design allows it, removing the static keyword lets you use getClass() normally. This makes sense if this navigation logic is tied to a specific controller or service object.
public void callNewScene(String sceneJump, Event event) throws IOException { ((Node)event.getSource()).getScene().getWindow().hide(); Stage primaryStage = new Stage(); FXMLLoader loader = new FXMLLoader(getClass().getResource(sceneJump)); Pane root = loader.load(); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); }
Now you'll call this method on an instance of your class instead of directly on the class itself.
内容的提问来源于stack exchange,提问作者i4mB4rney 02

