Set background image the same size as the window/screen in Java app


I would like to set a background image the same size as my window/screen.

I would prefer to do this in my CSS file, but I have NOT FOUND a way to accomplish this.

Must I do this in a javafx class file?

Thanks for every help ;)

5/8/2014 1:15:41 PM

Accepted Answer

You will have to determine the screen size in java code as demonstrated in JavaFX window sizing, there is no way to determine it in CSS.

For an Image, in your java code you can use something as

ImageView imageView = new ImageView(image);

If you want to set the background image to a scene then:

import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.*;

public class ScreenSizeImage extends Application {
    @Override public void start(final Stage stage) {
        // uncomment if you want the stage full screen.

        Screen screen = Screen.getPrimary();
        Rectangle2D bounds = screen.getVisualBounds();


        StackPane root = new StackPane();
            "-fx-background-image: url(" +
                "''" +
            "); " +
            "-fx-background-size: cover;"
        stage.setScene(new Scene(root));;

    public static void main(String[] args) { launch(args); }

Of course, rather than the inline setStyle call you are best off using a separate CSS stylesheet like below:

    -fx-background-image: url("background_image.jpg");
    -fx-background-size: cover;
5/23/2017 12:17:42 PM

Good question...

  • Firstly, I think you mean "the size of your app window" in your question. Obviously, you can't have a background image that is larger than your screen if you app window is smaller.

  • Secondly, here's a snippet from the JavaFX CSS Reference Guide:

    "...the background and border mechanisms are patterned after the CSS 3 draft backgrounds and borders module. See [4] for a detailed description."


    [4] CSS Backgrounds and Borders Module Level 3:

    • You can use the JavaFX vendor specific CSS property -fx-background-size with the stretch value as long as your aspect ratio is correct/your dimensions are proportional.
    • You might also get it to work by trying a combination of auto for one dimension and 100% for another... and some combination of contain... depending on if you can live with a cropped image.

    • -fx-background-size<bg-size> [ , <bg-size> ]*

      <bg-size> = [ <size> | auto ]{1,2} | cover | contain | stretch

      A series of values separated by commas. Each bg-size item in the series applies to the corresponding image in the background-image series.

    • You can get more detail at

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow