2

When I attempted to change the folder where my css files were located, I got this error:

WARNING: com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged Resource "file:/C:/[path-to-project]/Test/resources/css/main.css" not found.

I copied the URL and pasted it into the file manager and it opened the file, so I know it exists.

public static void main(String[] args)
{
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception
{
    primaryStage.setTitle("New Window");

    Scene scene = new Scene(new AnchorPane(), 800, 600);
    primaryStage.setScene(scene);

    URL css = new URL("file:///" + 
            new File("resources/css").getAbsolutePath().replace("\\", "/") + 
            "/main.css");
    scene.getStylesheets().clear();
    scene.getStylesheets().add(css.toExternalForm());

    primaryStage.show();
}

This is my eclipse project layout [also as an image]:

Test
├───src
│   └───com
│       └───Client.java
├───JRE System Library [JavaSE-1.8]
└───resources
    └───css
        └───main.css

I have tried:

scene.getStylesheets().add(getClass().getResource("/resources/css/main.css")); 
scene.getStylesheets().add(getClass().getResource("resources/css/main.css"));
scene.getStylesheets().add(getClass().getResource("../resources/css/main.css"));

I also tried using fxml to add the css files trying:

stylesheets="@../resources/css/main.css"
stylesheets="@/resouces/css/main.css"
stylesheets="@resources/css/main.css
2
  • You should add your resources path to your classpath in Eclipse. Commented Jul 2, 2016 at 23:27
  • old but for the ocassional reader: For Jigsaw there is a FIXME note in the javafx source: "/ FIXME: JIGSAW -- use Class.getResourceAsStream if resource is in a module". Lets hope they fix that soon. Commented Apr 8, 2019 at 20:57

1 Answer 1

12

Put your main.css file inside resources/com directory (so resources + package of the class loading it) and then you can use a simple (assuming your class is named Client and it is in the com package):

scene.getStylesheets().add(Client.class.getResource("main.css").toExternalForm());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.