Home > Enterprise >  Null Pointer Exception when loading CSS file in JavaFX
Null Pointer Exception when loading CSS file in JavaFX

Time:12-17

This might be a very easy fix, I'm entirely new to JavaFX and CSS and I'm trying to add some CSS to my Scene. The build runs, but the CSS obviously isn't working and I get a Null Pointer Exception in javafx.css.CssParser.



@font-face{ 
    font-family:'Quentin';
    src: url('/ui/font/Quentin.otf');
}


.textfield{

-fx-font-family: 'Quentin';

}

.button{ 
    -fx-font-family: 'Quentin';
    -fx-text-fill: blue;
}

.textfield{
    -fx-background-color: null;
}

When I remove the @font-face block, the rest of the code runs fine and my buttons and text fields work and appear as expected. I'm not sure if the tutorials I'm looking up are following an old Java tutorial which is now updated.

For reference, the font 'Quentin' appears to be downloaded as Quentin.otf, but appears in the file explorer as Quentin-Regular.otf, as pictured. Quentin Font Properties Quentin Font in File Explorer

I have tried changing the file names to both instances, but no dice. Any help would be appreciated!

CodePudding user response:

Firstly, if your src folder structured something similar to this:

├── main
     ├── java
     |     └── ...
     |
     └── resources
             |
             ├── fonts
             |     └── Quentin.otf
             |
             └── stylesheet.css

Then in your stylesheet the font src will be:

@font-face {
    font-family: 'Quentin';
    src: url('fonts/Quentin.otf');
}

Secondly, the TextField style class is .text-field not .textfield.

Thirdly, -fx-font-family: 'Quentin'; and -fx-background-color: null; can be in the same CSS block because they have the same class (.text-field).

@font-face {
    font-family: 'Quentin';
    src: url('fonts/Quentin.otf');
}

.text-field {
    -fx-font-family: 'Quentin';
    -fx-background-color: null;
}

.button {
    -fx-font-family: 'Quentin';
    -fx-text-fill: blue;
}

Finally, you may want to add the stylesheet to a pane pane.getStylesheets().add("stylesheet.css");

Good luck.

  • Related