0

I'm still pretty new to JavaFX, but I discovered style sheets recently and found that you can use it to set the design of your application. I wanted to see if I could change the background of my app to an image. This is my current project setup:

16copia.jpg is what I want to set the background to.

tree

And this is my style.css setup.

.root{
    -fx-font-family: 'JetBrains Mono';
    -fx-font-size: 10px;
    -fx-background-image: url("16copia.jpg");
    -fx-background-repeat: no-repeat;
    -fx-background-size: stretch;

}
.button{
    -fx-base:lightblue;
}
.label {
    -fx-text-fill: lightblue;
}

In my main class, I added the style sheet to my main scene. Also tried using root.setStyle, but to no avail.

public void start(Stage stage){
    stage.setTitle("Calculator App");
    genMenuBar();
    setFunctionality();

    Scene mainScene = new Scene(root, 300, 500);
    root.setBottom(calcView);
    root.setCenter(displayView);
    mainScene.getStylesheets().add("style.css");
    stage.setScene(mainScene);
    stage.show();
    //root.setStyle("-fx-background-image: url('src/main/java/calculator/app/16copia.jpg');");
}

When I run the program, all of the CSS styling except for the image is applied.

Not meant to be the final look, mostly just experimenting with style sheets:

screen

The program runs with no errors, but the bug persists. I'd prefer to stick to CSS styling if possible.

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • An image is a resource, not source, so put it in the resources folder. If you put it in the same folder as the css, you should be able to reference it by name without folders the path. – jewelsea Nov 19 '22 at 04:20
  • See the [eden resource guide](https://edencoding.com/where-to-put-resource-files-in-javafx/). – jewelsea Nov 19 '22 at 04:21
  • 1
    You should never have `src/main/java` in a resource lookup string, that is a path in your project source, not your runtime execution resource path. – jewelsea Nov 19 '22 at 04:25

1 Answers1

1

Moving the image to the resources folder and replacing the path string with just the name of the file seems to have fixed the issue. Thanks @jewelsea!

Here are the modifications for reference.

.root{
    -fx-font-family: 'JetBrains Mono';
    -fx-font-size: 10px;
    -fx-background-image: url("16copia.jpg");
    -fx-background-size: stretch;    
}

Moved 16copia.jpg to resources folder:

tree

jewelsea
  • 150,031
  • 14
  • 366
  • 406