Problem
I want to set a background image in my JavaFX GUI. The GUI should be resizable to any ratio so that my background image must stretch in both directions (while changing the ratio between width and height of the background image)
Inspired by another stackoverflow post I found out how to do this by css:
.root {
-fx-background-image: url('http://icons.iconarchive.com/icons/iconka/meow/256/cat-box-icon.png');
-fx-background-size: stretch;
}
But I have the constraint that my background image is created dynamically as a BufferedImage
.
First approach
Thus I startet to set my background image by code instead of css like this:
Region region = // ...
BufferedImage bufferedBackgroundImage = // ...
WritableImage fxImage = new WritableImage(bufferedBackgroundImage.getWidth(), bufferedBackgroundImage.getHeight());
SwingFXUtils.toFXImage(bufferedBackgroundImage, fxImage);
region.setBackground(
new Background(
new BackgroundImage(
fxImage,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,
new BackgroundSize(BackgroundSize.AUTO, BackgroundSize.AUTO, false, false, false, true))));
Unfortunately my background does not stretch anymore. I tried several combinations of booleans within the BackgroundSize and several BackgroundRepeat constants but I was only able to stretch my background image in one instead of both directions.
Second approach
I tried to set the background image with the code of my first approach and then add stylesheets with
region.setStyle("-fx-background-size: stretch;");
But then the background image disappeared at all. I think this is because of the setStyle
instead of addStyle
so I overwrite it.
The following code did not work as well. I think because you can set URLs to css files only but no styles.
region.getStylesheets().add("-fx-background-size: stretch;");
Question
I would appreciate ideas how I can go further.