How to make canvas Resizable in javaFX?

前端 未结 6 1677
执笔经年
执笔经年 2020-12-09 10:36

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         


        
6条回答
  •  醉梦人生
    2020-12-09 11:35

    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:

    • I didn't want to break encapsulation by forcing the parent component to send us a width and height in the constructor which would also mean that the canvas cannot be used in FXML.
    • I also did not want to depend on the parent's width and height properties thus making the canvas the only child in it's parent, by taking up all the space.
    • Finally, the canvas needed to have it's drawing done in another class, which meant I could not use the current accepted answer which also included drawing to canvas via a draw method.

    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.

提交回复
热议问题