1

I can't set a background image for a Hbox. I tried this:

HBoxName.setStyle("-fx-background-image: images/background.png");

in the initialize method and then I also tried adding the CSS style in Scene Builder: -fx-background-image and url("images/background.png"). How can I do it?

saeed foroughi
  • 1,662
  • 1
  • 13
  • 25
coder002
  • 37
  • 1
  • 9
  • 2
    Does this answer your question? [JavaFX How to set scene background image](https://stackoverflow.com/questions/9738146/javafx-how-to-set-scene-background-image) – Shekhar Rai Jan 18 '20 at 17:17
  • Where do I create the css file? In the source package of the project? and what I have to write in this file? – coder002 Jan 19 '20 at 14:04

1 Answers1

1

There is a couple of ways to set a background image for your HBox,

1. Using CSS

  • Using setStyle method

    Use setStyle() method to set a background image directly,

    HBoxName.setStyle("-fx-background-image: url('images/background.png');" +
            "-fx-background-repeat: stretch;" +
            "-fx-background-size: 1000 700;" +
            "-fx-background-position: center center;");
    
  • Using external CSS file

    You should create an external CSS file load it to your scene(or you can load CSS file to any control as well),

    scene.getStylesheets().add(
        this.getClass().getClassLoader().getResource("style.css").toString()
    );
    

    Add these styles in your style.css file,

    #HBoxName{
       -fx-background-image: url("images/background.png");
       -fx-background-repeat: stretch;   
       -fx-background-size: 1000 700;
       -fx-background-position: center center; 
    }
    

    References

2. Setting BackgroundImage using setBackground()

You can set a background-image with programmatically as well.

BackgroundSize backgroundSize = new BackgroundSize(900,
        700,
        true,
        true,
        true,
        false);
BackgroundImage image = new BackgroundImage(new Image("image/background.png"),
        BackgroundRepeat.NO_REPEAT,
        BackgroundRepeat.NO_REPEAT,
        BackgroundPosition.CENTER,
        backgroundSize);

HBoxName.setBackground(new Background(image));
Shekhar Rai
  • 2,008
  • 2
  • 22
  • 25