18

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.

Danielle
  • 181
  • 1
  • 1
  • 6

18 Answers18

26

put your yourname.css file directly under src directory.

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

clean and build required

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
nikolaos
  • 277
  • 3
  • 3
  • 4
    I think it's more beautiful and clear if you put it in a subdir. not directly under `/src` – deepthought-64 Dec 12 '16 at 10:04
  • @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? – Kennerdol Dec 25 '22 at 09:12
  • 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 https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html how maven structures their projects – deepthought-64 Jan 02 '23 at 15:32
16

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();
Korki Korkig
  • 2,736
  • 9
  • 34
  • 51
  • 1
    Why we need to use toExternalForm(); method in the last? – Asif Mushtaq Jul 25 '16 at 07:20
  • @UnKnown `node.getStylesheets().add()` don't accept `URL` object as parameter. `toExternalForm()` represent it as string. – Ari Jul 20 '17 at 08:35
  • 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." – Line Jan 26 '18 at 11:22
  • what is 'root'? Is it the 'src' directory? – Sourav Kannantha B Aug 12 '21 at 07:23
  • 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 – clockw0rk May 06 '22 at 13:58
10

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.

Alex
  • 11,451
  • 6
  • 37
  • 52
JBR
  • 101
  • 1
  • 2
  • 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 – clockw0rk May 06 '22 at 14:03
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.

fanatek
  • 71
  • 1
  • 3
6

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())
xyman
  • 399
  • 3
  • 10
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. :)

Bruno Toffolo
  • 1,504
  • 19
  • 24
ayoub soso
  • 41
  • 1
  • 3
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

1

It's pretty much simple.

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

This is what worked for me-

0

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

Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
  • Yes, I'm using Netbeans. I've tried "clean and build" multiple times, but it doesn't solve the problem. – Danielle Dec 19 '12 at 18:52
  • @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. – Uluk Biy Dec 19 '12 at 19:26
  • 1
    The NullPointerException is generated by the first line. – Danielle Dec 19 '12 at 19:35
  • 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.");} – Danielle Dec 19 '12 at 19:45
  • Even so I insist you to create a new small project in Netbeans and retry loading your css file there. – Uluk Biy Dec 19 '12 at 20:53
  • I made a new small project, and appear to have the exact same problem. :( – Danielle Dec 19 '12 at 21:14
0

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

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

medokr
  • 441
  • 1
  • 5
  • 16
  • Yes, the scene is initialized. – Danielle Dec 19 '12 at 22:30
  • 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. – medokr Dec 19 '12 at 22:34
  • 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. – medokr Dec 19 '12 at 22:40
  • If you have not had success, try to copy / paste the project at http://www.javadesk.co/css/javaFXCssIntro.html. There is one java file and two css files to copy into your project. – medokr Dec 19 '12 at 23:54
  • Have you had success with your problem? – medokr Dec 30 '12 at 23:21
0

in your file .java use this

Application.setUserAgentStylesheet(getClass().getResource("application.css")
                .toExternalForm());
AVI
  • 5,516
  • 5
  • 29
  • 38
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());
Jolaade Adewale
  • 326
  • 5
  • 10
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());
B. Freeman
  • 135
  • 1
  • 2
  • 8
0
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

Pacho
  • 36
  • 2
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());

Malith Ileperuma
  • 926
  • 11
  • 27
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>
derloopkat
  • 6,232
  • 16
  • 38
  • 45
anto
  • 1
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

Long tran
  • 71
  • 1
  • 2
-1

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

ex: '@main.css'