In javaFX to resize a canvas there is no such method to do that, the only solution is to extends from Canvas.
class ResizableCanvas extends Canvas {
pub
Of all the answers given, none of them actually worked for me in terms of making the canvas automatically resize with its parent. I decided to take a crack at this and this is what I came up with:
import javafx.scene.canvas.Canvas;
public class ResizableCanvas extends Canvas {
@Override
public boolean isResizable() {
return true;
}
@Override
public double maxHeight(double width) {
return Double.POSITIVE_INFINITY;
}
@Override
public double maxWidth(double height) {
return Double.POSITIVE_INFINITY;
}
@Override
public double minWidth(double height) {
return 1D;
}
@Override
public double minHeight(double width) {
return 1D;
}
@Override
public void resize(double width, double height) {
this.setWidth(width);
this.setHeight(height);
}
}
This was the only one that actually made the canvas truly resizable.
My reasons for going with this approach is as follows:
width
and height
in the constructor which would also mean that the canvas cannot be used in FXML
.width
and height
properties thus making the canvas the only child in it's parent, by taking up all the space.With this canvas, I do not need to bind to its parent width/height properties to make the canvas resize. It just resizes with whatever size the parent chooses. In addition, anyone using the canvas can just bind to its width/height properties and manage their own drawing when these properties change.