JavaFX加载FXML无报错但白屏,CSS未生效求助
Hey there! Let's troubleshoot your JavaFX white screen and CSS not loading issue—this is super common with Java 8 + JFoenix setups, so I’ve got some targeted fixes to walk you through:
Resource path mismatches are the #1 culprit here. Let’s confirm your files are where your code expects them to be:
- Add debug prints to verify if your resources are actually being found:
If either outputsSystem.out.println("FXML path: " + Main.class.getResource("/fxml/loginscreen.fxml")); System.out.println("CSS path: " + getClass().getResource("/styles/dark-theme.css"));null, your path is wrong. For a standard Maven/Gradle project, make sure:loginscreen.fxmllives insrc/main/resources/fxml/dark-theme.csslives insrc/main/resources/styles/
JFoenix 8.0.1 relies on its internal default styles to render components properly—and clearing the stylesheet list can wipe those out, leading to broken rendering or white screens. Try this adjusted code:
FXMLLoader loader = new FXMLLoader(); URL loc_login = Main.class.getResource("/fxml/loginscreen.fxml"); loader.setLocation(loc_login); try { this.rootLayout = loader.load(); } catch (IOException e) { e.printStackTrace(); // Catch any FXML loading failures } Scene scene = new Scene(rootLayout); // Skip the clear() call—don't remove JFoenix's default styles scene.getStylesheets().add(getClass().getResource("/styles/dark-theme.css").toExternalForm()); // Optional: Initialize JFoenix's component styles explicitly (helps with consistency) JFXSnackbar.registerSnackbarContainer(rootLayout); primaryStage.setScene(scene); primaryStage.centerOnScreen(); primaryStage.show();
A white screen might not be a CSS issue at all—it could just be that your root container isn’t sized properly:
- Open your FXML in SceneBuilder, select the root pane (e.g.,
AnchorPane,JFXPane), and setprefWidth/prefHeightto concrete values (like 800x600), or check "Resizable" and bind it to the scene. - Alternatively, set the scene size explicitly in code:
Scene scene = new Scene(rootLayout, 800, 600);
JFoenix uses custom CSS selectors—regular JavaFX selectors won’t work for its components. For example:
/* Wrong (won't style JFXButton) */ .button { -fx-background-color: red; } /* Correct (targets JFoenix's button component) */ .jfx-button { -jfx-button-type: RAISED; -fx-background-color: #2196F3; -fx-text-fill: white; }
Also, Java 8’s CSS engine doesn’t support modern features like var() variables—strip those out if you’re using them.
Sometimes FXML fails to load (e.g., typo in a component import) but doesn’t throw an obvious error, leaving you with an empty root node. The try/catch block I added earlier will print the full stack trace, which will point you to issues like missing JFoenix components or invalid FXML syntax.
内容的提问来源于stack exchange,提问作者BlurredDev

