9

I'm trying to set an image as the background using this code:

root.setStyle("-fx-background-image: url('splash.jpg'); 
               -fx-background-position: center center; 
               -fx-background-repeat: stretch;");

But it doesn't work. If I set it with CSS, it works perfectly:

root.setId("pane");
primaryStage.getScene().getStylesheets().add(JavaFXApplication9.class.getResource("style.css").toExternalForm());

and CSS:

#pane{
   -fx-background-image: url('splash.jpg');
   -fx-background-repeat: stretch;   
   -fx-background-position: center center;
}

All of my files (main class, CSS and image) placed into the same package.

So, how can I set the background image using code? Or, how can I override (replace) lines about background-image of some element in CSS from application code? Thanks!

SpaceCore186
  • 586
  • 1
  • 8
  • 22
Gleb
  • 731
  • 1
  • 8
  • 14

2 Answers2

17

Try next:

String image = JavaFXApplication9.class.getResource("splash.jpg").toExternalForm();
root.setStyle("-fx-background-image: url('" + image + "'); " +
           "-fx-background-position: center center; " +
           "-fx-background-repeat: stretch;");
Sergey Grinev
  • 34,078
  • 10
  • 128
  • 141
16

If you really don't want to use CSS or the setStyle() method, you can use the following:

// new Image(url)
Image image = new Image(CurrentClass.class.getResource("/path/to/package/bg.jpg"));
// new BackgroundSize(width, height, widthAsPercentage, heightAsPercentage, contain, cover)
BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false);
// new BackgroundImage(image, repeatX, repeatY, position, size)
BackgroundImage backgroundImage = new BackgroundImage(image, BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize);
// new Background(images...)
Background background = new Background(backgroundImage);

You can find detailed documentation on BackgroundImage here.

(Sorry for replying to this old question.)

machinateur
  • 502
  • 5
  • 10
  • This just makes a blank VBox for me: https://pastebin.com/s71vYfDM – Monty Dec 17 '19 at 20:09
  • @JoshDiamond it looks to me as if the url given to the constructor of `new Image(...)` might not be correct in your code. Have you tried using `getResource(...)` instead? – machinateur Dec 19 '19 at 07:47