Issue
I recently wanted to create an animated background in JavaFX, similar to the Swing example seen here. I used a Canvas
on which to draw, as shown in Working with the Canvas API, and an AnimationTimer
for the drawing loop, as shown in Animation Basics. Unfortunately, I'm not sure how to resize the Canvas
automatically as the enclosing Stage
is resized. What is a good approach?
A similar question is examined in How to make canvas Resizable in javaFX?, but the accepted answer there lacks the binding illustrated in the accepted answer here.
Solution
I combined both prior solutions ( @trashgod and @clataq's ) by putting the canvas in a Pane and binding it to it:
private static class CanvasPane extends Pane {
final Canvas canvas;
CanvasPane(double width, double height) {
setWidth(width);
setHeight(height);
canvas = new Canvas(width, height);
getChildren().add(canvas);
canvas.widthProperty().bind(this.widthProperty());
canvas.heightProperty().bind(this.heightProperty());
}
}
Answered By - gerardw
Answer Checked By - Terry (JavaFixing Volunteer)