How to make canvas Resizable in javaFX?

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

    There's a guide that I think that you may find useful for setting up a resizable canvas:

    JavaFx tip - resizable canvas

    Piece of code from the guide:

    /**
     * Tip 1: A canvas resizing itself to the size of
     *        the parent pane.
     */
    public class Tip1ResizableCanvas extends Application {
    
        class ResizableCanvas extends Canvas {
    
            public ResizableCanvas() {
                // Redraw canvas when size changes.
                widthProperty().addListener(evt -> draw());
                heightProperty().addListener(evt -> draw());
            }
    
            private void draw() {
                double width = getWidth();
                double height = getHeight();
    
                GraphicsContext gc = getGraphicsContext2D();
                gc.clearRect(0, 0, width, height);
    
                gc.setStroke(Color.RED);
                gc.strokeLine(0, 0, width, height);
                gc.strokeLine(0, height, width, 0);
            }
    
            @Override
            public boolean isResizable() {
                return true;
            }
    
            @Override
            public double prefWidth(double height) {
                return getWidth();
            }
    
            @Override
            public double prefHeight(double width) {
                return getHeight();
            }
        }
    

提交回复
热议问题