Search code examples
javacssjavafxstylesheet

Stylesheet is not applied in JavaFx


I'm working on a JavaFX application, but I can't get the stylesheet to be applied.

My code:

public class JavaFX extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        //set up the stage
        primaryStage.initStyle(StageStyle.UNDECORATED);
        primaryStage.setMaximized(true);

        Group root = new Group();
        root.setId("root");
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        scene.getStylesheets().add(JavaFX.class.getResource("styling.css").toExternalForm());

        //Get the screensize
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        double screenX = screenSize.getWidth();
        double screenY = screenSize.getHeight();

        //Text objects
        Text text = new Text();
        text.setId("text");
        text.setText("Test");
        text.setY(50);

        //Add all objects to the root group
        root.getChildren().add(text);

        //Show the stage
        primaryStage.show();

        //Calculate Positions of all objects
        text.setX((screenX /2) - text.getBoundsInParent().getWidth());

My Stylesheet:

#text {
    -fx-font-size: 50px;
}

The CSS file is in the same package as the java file.

Any help would be appreciated!


Solution

  • Your code applies css correctly, at least I have checked with your font size and -fx-font-size: 500px; and "Text" changed as expected. Please check your styling.css file once again. (Additionally, you can always check what is compiled and look what is indeed in jar to check what is actually pulled into what you later run)

    The most possible, however is that maybe you have duplicate css files with the same name, one overriding another. E.g. one in resources folder and one in the same place as your .java file