Setting the background image using javafx code (not css)

I am trying to set the image as background using this code:

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

But that will not work. If I installed it using CSS, it works fine:

 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 my files (main class, CSS and image) are placed in the same package.

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

+6
source share
2 answers

Try the following:

 String image = JavaFXApplication9.class.getResource("splash.jpg").toExternalForm(); root.setStyle("-fx-background-image: url('" + image + "'); " + "-fx-background-position: center center; " + "-fx-background-repeat: stretch;"); 
+12
source

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); 

Detailed documentation can be found on BackgroundImage here .

(Sorry for the answer to this old question.)

+9
source

Source: https://habr.com/ru/post/911560/


All Articles