xeruf
xeruf

Reputation: 2990

JavaFX apply effect on a BackgroundImage

Situation

I am using a BackgroundImage to set the background for a JavaFX Region, like this:

region.setBackground(Background(BackgroundImage(Image(url)), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, BackgroundSize(100.0, 100.0, true, true, true, true))))

Problem

I would like to darken the background somehow so that the white font stays readable.

What I've tried

I have searched through Image, BackgroundImage and Background, but none have any way to add an effect. I found that I can add an effect directly to the Region, but when I add the ColorAdjust, it darkens everything, not just the background.

I really don't care at which layer it is set, it could even be in CSS, I simply want to somehow darken the BackgroundImage.

Upvotes: 3

Views: 650

Answers (1)

Slaw
Slaw

Reputation: 46036

When you apply an Effect to a node it affects all of its children, if it has any. You also can't apply an Effect to a Background specifically as it provides no API to do so1. Instead, what you can do is have a separate Region to use for your background image and then place it and your other content in a common parent. You could then apply the Effect to this "background region" and only affect it, not any other nodes. A parent that would work well for this situation is a StackPane since it will stack your other content above the "background region"; it will also resize the region to fill up all available space (making it effectively a background image).

// Can also apply background through CSS or FXML. Same with the
// effect, though only DropShadow and InnerShadow can be set through
// CSS—any effect can be set though FXML.
Region backgroundRegion = new Region();
backgroundRegion.setBackground(new Background(new BackgroundImage(...)));
backgroundRegion.setEffect(new ColorAdjust(...));

Node otherContent = ...;

StackPane parent = new StackPane(backgroundRegion, otherContent);
// add "parent" to scene graph...

Note I'd use a Region, like above, rather than an ImageView as the former will keep the behavior of a background image; it's not that easy to imitate a background image with an ImageView (at least in my experience).


1. This applies to code, CSS, and FXML. Note that CSS and FXML are just alternative ways to creating a Background object.

Upvotes: 2

Related Questions