Reputation: 1894
This stackoverflow answer explains how to put a background image inside a TextField. However, I would like to know how to put arbitrary text as background, and do it without CSS, if possible. My first idea was to take a snapshot of Text node and use it as a background image, as follows (I am doing this inside a constructor of a class extending TextField):
Text text = new Text("TEST");
text.setFill(Color.RED);
WritableImage image = text.snapshot(new SnapshotParameters(), null);
this.setBackground(new Background(
new BackgroundImage(
image,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
new BackgroundPosition(Side.LEFT, 3D, false, Side.TOP, 50, true),
new BackgroundSize(image.getWidth(), image.getHeight(), false, false, false, false))));
However, it doesn't work. Background gets completely grayed out, and even the border disappears. Any idea how to do this? CSS solution is also acceptable.
Upvotes: 1
Views: 789
Reputation: 1894
I figured it out. Sometimes it helps to just put the question here, it gets you thinking. :-)
There were three problems. First, I had to use existing background as a base for new background. Second, I used vertical position incorrectly, I thought if you set it to 50% it will center it vertically, but apparently not. And finally, you can't do this in constructor because background doesn't exist yet, so I had to wrap it inside Platform.runLater(). Here is the revised code.
Platform.runLater(new Runnable() {
@Override
public void run() {
Text text = new Text("TEST");
text.setFill(Color.RED);
WritableImage image = text.snapshot(new SnapshotParameters(), null);
double imageVPos = (getHeight() - image.getHeight()) / 2;
BackgroundImage backImage = new BackgroundImage(
image,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
new BackgroundPosition(Side.LEFT, 7D, false, Side.TOP, imageVPos, false),
new BackgroundSize(image.getWidth(), image.getHeight(), false, false, false, false));
List<BackgroundImage> images = new ArrayList<BackgroundImage>();
images.add(backImage);
setBackground(new Background(getBackground().getFills(), images));
}
});
Upvotes: 0