20

Language: JavaFX

IDE: Netbeans

Problem: I'm trying to add a css file to the stylesheet, but the first line of the following code always generates a NullPointerException:

String css = this.getClass().getResource("double_slider.css").toExternalForm(); 
scene.getStylesheets().add(css);

I've tried replacing "double_slider.css" with the full path. double_slider.css is currently located in the same package as the class that makes this call. I've also tried all of the variations found at http://introjava.wordpress.com/2012/03/21/linking-a-css-style-sheet-to-javafx-scene-graph/, with no success. Clean and build doesn't help either.

If I place the css file in the build folder where the .class files are dumped, the NullPointerException goes away. But then the css file does not work properly because it references other files in my project.

1
  • How is your app built, deployed and executed? Commented Dec 19, 2012 at 16:48

18 Answers 18

27

put your yourname.css file directly under src directory.

scene.getStylesheets().add("yourname.css")

clean and build required

Sign up to request clarification or add additional context in comments.

3 Comments

I think it's more beautiful and clear if you put it in a subdir. not directly under /src
@deepthought-64 if I put it under the application directory I'm getting WARNING: Resource "/application/stylesheet.css not found. but if I put it under the src folder it works fine, what could be the explanation for this?
you need to put it in a folder where the compiler (or any build tool) will copy it to the output directory. usually everything under /src will be compiled or copied. normally you also have directories for resources. you can't put code or resources directly in the app directory (the folder where also your /src lies) because this will not be looked into by the compiler / build-tool. see maven.apache.org/guides/introduction/… how maven structures their projects
20

I think your're missing the slashes which causes that the CSS file can't be found. Try to correct your path reference.

For example:

-root
--app/Main.java
--assets/double_slider.css

would be:

String css = this.getClass().getResource("/assets/double_slider.css").toExternalForm();

5 Comments

Why we need to use toExternalForm(); method in the last?
@UnKnown node.getStylesheets().add() don't accept URL object as parameter. toExternalForm() represent it as string.
from the JavaDoc: "Any leading '/' character of the [path] is ignored and the [path] is treated as a path relative to the root of the application's classpath."
what is 'root'? Is it the 'src' directory?
u can always check from which directory the application is running with System.getProperty("user.dir"); ..... this will be handy when deploying the application to target device, to make sure you always have the correct pathing to subdirectories with your resources. U can pass different strings for different purposes there, but i will not google that for you
11

I had the same problem. I use NetBeans 7.3 and JavaFX 2.2.7, JDK 7.0_21 on Win7.

My solution was to place the .css in the SAME folder as my Java file containing void start(Stage stage). So the Project view looks like this:

  • ProjectName
    • Source Packages
      • pkgWhatever
        • Main.java
        • MyCssFile.css

(So the CSS file is IN the package, which I find really weird and contraintuitive. Some doc told me to put it in the root of the project so it could be found at runtime, but that didn't work for me in NB. My app now runs regardless of whether I start the file containing "start(..)" by hitting Ctrl+U or clicking Run on the project's context menu. And it doesn't matter whether I let NB put everything into a JAR or not.)

Here's the code that loads the CSS in the above situation:

  URL url = this.getClass().getResource("controlStyle1.css");
    if (url == null) {
        System.out.println("Resource not found. Aborting.");
        System.exit(-1);
    }
    String css = url.toExternalForm(); 
    scene.getStylesheets().add(css);

Whereas this didn't work:

    scene.getStylesheets().add("controlStyle1.css");

Hope this helps.

1 Comment

u could read into "how to determine java runtime path", I always had a seperate asset folder for developement-time-loading and one for deployment-time-loading. hint: as i stated in comment above, try System.getProperty("user.dir") once in IDE and once from JAR file and see the difference
10

All of the answers are missing one very important part and that's '/' before the name of the css file:

Folder structure:

src
  resources
    stylesheet.css

Load it like this, notice the starting slash before css file:

scene.getStylesheets().add(getClass().getResource("/stylesheet.css").toExternalForm())

Comments

7

I had the same problem (in NetBeans 8). I found a solution here : https://blog.idrsolutions.com/2014/04/use-external-css-files-javafx/

My resource file spreadsheet.css was here :

MyApp
-resources
--spreadsheet.css
-source packages
--fr.ccc.myapp.view
---mainView.java
---FXMLMain.fxml

In mainView.java :

File f = new File("resources/spreadsheet.css");
spreadsheet.getStylesheets().add("file:///" + f.getAbsolutePath().replace("\\", "/"));

Hope this helps.

Comments

2

Considering your old code:

String css =this.getClass().getResource("double_slider.css").toExternalForm(); 
scene.getStylesheets().add(css);

Try changing it to this new code and it will work:

screen.getStylesheets().add(getClass().getResource("double_slider.css").toExternalForm());

When you use getClass(), you don't need to use this keyword.

I hope this work for you. :)

Comments

2

You can add your style.css directly in your .fxml file as an attribute to your root element as this stylesheets="@your_relative_path/style.css".

You can use @../style.css if you want to access the css file that is in your src folder

Comments

1

It's pretty much simple.

this.scene.setUserAgentStylesheet(/resources/blabla.css);

This is what worked for me-

Comments

1
scene.getStylesheets().add("file:///home/fullpathname/file.css");

or

scene.getStylesheets().add("file:/home/fullpathname/file.css");

but after:

Run / Clean and Build Project

worked for me

NetBeans IDE 8.2 ; Java: 1.8.0_201 ;Linux 16.04

Comments

0

Hmmm, are you on Netbeans? Try to "Clean and Build" the project.

6 Comments

Yes, I'm using Netbeans. I've tried "clean and build" multiple times, but it doesn't solve the problem.
@Danielle. Which of the following lines generate NullPointerException: 1) String css = this.getClass().getResource(“double_slider.css”).toExternalForm(); 2) scene.getStylesheets().add(css);. If still in 2nd then you need provide more details. Alternatively create a new small project in Netbeans and retry loading your css file there.
The NullPointerException is generated by the first line.
I also know Netbeans can find the file. I checked using the following code, where path is the complete path to the css file: File f = new File(path); if(f.exists()) {System.out.println("File exists.");}
Even so I insist you to create a new small project in Netbeans and retry loading your css file there.
|
0

Have you initialized the scene object prior to setting style sheet?

scene = new Scene(myRootLayout, 600, 600); // for example

5 Comments

Yes, the scene is initialized.
I had a similar problem when working with the CSS, I am having a hard time remembering what was wrong. Initializing the scene was one way to throw the Null Pointer exception.
Did you paste the code above directly from your source code? The quotes around double_slider.css look awkward. Can you try retyping those quotation marks. Might be an odd suggestion. The code appears correct to me.
If you have not had success, try to copy / paste the project at javadesk.co/css/javaFXCssIntro.html. There is one java file and two css files to copy into your project.
Have you had success with your problem?
0

in your file .java use this

Application.setUserAgentStylesheet(getClass().getResource("application.css")
                .toExternalForm());

Comments

0

Folder Structure

In the MedicalLibraryFx.java

scene.getStylesheets().add(getClass().getResource("/css/style.css").toString()); 

Folder structure when css is in the same directory as controller

scene.getStylesheets().add(getClass().getResource("style.css").toString());

Comments

0

Assuming the file structure is something like this:
-root
--src
---resources
----double_slider.css
---package
----JavaFXFile.java

This is what worked for me:

scene.getStylesheets().add((new File("src/resources/double_slider.css")).toURI().toString());

Comments

0

I made a small login example and this is how i link my styleshet.css

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("LoginUI.fxml"));


    Scene scene = new Scene(root);

    scene.getStylesheets().add(JavaFXLogin.class.getResource("stylesheet.css").toExternalForm());

    stage.setScene(scene);
    stage.show();

}

You can use this code line to link your css file. but the css file should be in your package.

scene.getStylesheets().add(JavaFXLogin.class.getResource("stylesheet.css").toExternalForm());

Comments

0

In a maven project you must define path for resources in the file.pom in the javafx-plugin section: something like this:

<configuration>
    <mainClass>com.personale.ciaomondo.App</mainClass>
          <resources>          
            <resource>
              <directory>src/main/resources</directory>
            </resource>
          </resources>
</configuration>

Comments

0

i don't know but i use intellij

i use


String css = (getClass().getResource("application.css")).toExternalForm();

but it resolves nullpointer exception

i use with getClassLoader() method

String css = (getClass().getClassLoader().getResource("application.css")).toExternalForm();

and it works

Comments

-1

Try putting '@' the name of the file. It worked for me.

ex: '@main.css'

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.