Loading css using JavaFX null pointer exception in eclipse

后端 未结 4 1120
感情败类
感情败类 2021-01-20 15:24

I\'m trying to load a CSS file into JavaFX using this line of code and it gives me a null pointer exception:

scene.getStylesheets().add(welcome.class.getReso         


        
相关标签:
4条回答
  • 2021-01-20 15:26

    Any resource should be on the classpath to be loaded successfully (if it is in the same folder as you welcome class then it is already so). Then you should precede the path to the stylesheet file by '/' symbol, so that it looks like this:

    scene.getStylesheets().add(welcome.class.getResource("/background.css").toExternalForm());
    

    Then it will load successfully.

    0 讨论(0)
  • 2021-01-20 15:46

    So I know this an old question, but I had a similar issue to this recently so I'd like to give what I think is the answer:

    Three conditions must be met to use a JavaFX file and a CSS file together:

    1. both JavaFX file and CSS file must both be in same directory
    2. You must declare in your code you are using the CSS file such as

        scene.getStylesheets().add(welcome.class.getResource("background.css").toExternalForm());
      
    3. And the thing I think was being left out is package PackageName;

      package YourPackageName;.
      Will be at the top of your JavaFX file before the place where you define your imports. This is something that could be easily forgotten if you are not used to working with multiple files in Java or if you start your code from scratch. Not having the package YourPackageName; does not stop your base file from working, but it can stop your program from running when you try to use your own defined CSS files.

    0 讨论(0)
  • 2021-01-20 15:51

    Did you initialize the Scene object yet?

    //Create a scene object. Pass in the layout and set with and height
    this.scene = new Scene(layout, 600, 400);
    
    //Add CSS Style Sheet (located in same package as this class).
    String css = this.getClass().getResource("background.css").toExternalForm();
    scene.getStylesheets().add(css);
    
    0 讨论(0)
  • 2021-01-20 15:51

    I had the same error than you... And here is the solution I found... if you have a Main class , replace the "welcome" by Main to get this code:

    The tree in Eclipse with JavaFX 2.0:

    -MyJavaProject            (JavaProject)
     | -src                   (Folder)
         | -Appli             (Package)
            |  -Main.java     (Class Main)
            |  -application.css  (css file)
    

    code for this tree:

    scene.getStylesheets().add(
              Main.class.getResource("application.css").toExternalForm());
    

    Hope this will help... ;)

    0 讨论(0)
提交回复
热议问题