CodexBloom - Programming Q&A Platform

Eclipse 2023-09: Errors in JavaFX Application When Using Custom CSS Stylesheets

👀 Views: 499 💬 Answers: 1 📅 Created: 2025-06-14
JavaFX Eclipse CSS NullPointerException Java

Can someone help me understand I've encountered a strange issue with I'm sure I'm missing something obvious here, but I am developing a JavaFX application in Eclipse 2023-09 and working with issues when applying custom CSS styles to my components..... My CSS file is located in the `src/main/resources` directory, and I am trying to load it with the following code: ```java import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class MyApp extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction(event -> System.out.println("Hello World!")); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root, 300, 250); // Loading custom CSS scene.getStylesheets().add(getClass().getResource("/styles.css").toExternalForm()); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } } ``` When I run the application, I get the following behavior in the console: ``` java.lang.NullPointerException: want to invoke "java.net.URL.toExternalForm()" because "url" is null ``` I have confirmed that the `styles.css` file exists in the `src/main/resources` directory and is properly included in the build path. To troubleshoot, I also tried using: ```java scene.getStylesheets().add("file:src/main/resources/styles.css"); ``` but that didn't work either. I’ve cleaned the project, refreshed the project files, and made sure that the resource is marked for export in the build properties. It seems like the URL for the CSS file is not being resolved correctly. Does anyone have any suggestions on how to properly reference the CSS file in this version of Eclipse for a JavaFX application? Is there perhaps a known scenario with resource loading in this Eclipse version? I'm working on a application that needs to handle this. What's the best practice here? Has anyone else encountered this? I'm using Java latest in this project. I'm coming from a different tech stack and learning Java.