How to make canvas Resizable in javaFX?

前端 未结 6 1699
执笔经年
执笔经年 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:32

    The canvas class just needs to override isResizable() (everything else, which is suggested in other examples, is actually not necessary) :

    public class ResizableCanvas extends Canvas
    {
      public boolean isResizable()
      {
          return true;
      }
    }
    

    And in the Application the width and height properties of the canvas have to be bound to the canvas' parent:

    @Override
    public void start(Stage primaryStage) throws Exception
    {
        ...
        StackPane pane = new StackPane();
        ResizableCanvas canvas = new ResizableCanvas(width, height);
    
        canvas.widthProperty().bind(pane.widthProperty());
        canvas.heightProperty().bind(pane.heightProperty());
    
        pane.getChildren().add(_canvas);
        ...
    }
    

    Listeners can be added to the width in height properties, in order to redraw the canvas, when it is resized (but if you need that and where to place it, depends on your application):

    widthProperty().addListener(this::paint);
    heightProperty().addListener(this::paint);
    

提交回复
热议问题