玩转算法(三)设置画布与图形绘制基础

在算法二中,我们已经通过两种方法创建出来一个画布,现在这一节中,我们在画布中添加一个圆形

实现效果


下面就看看是如何实现的。

首先主函数


然后实现



最后完整代码。

public class AlgoFrame extends JFrame{

    private int canvasWidth;
    private int canvasHeight;

    public AlgoFrame(String title, int canvasWidth, int canvasHeight){

        super(title);

        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;

        //setSize(canvasWidth, canvasHeight);
        AlgoCanvas canvas = new AlgoCanvas();
        // canvas.setPreferredSize(new Dimension(canvasWidth,canvasHeight));
        setContentPane(canvas);
        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        setVisible(true);

        // System.out.println(getContentPane().getBounds());
    }

    public AlgoFrame(String title){

        this(title, 1024, 768);
    }

    public int getCanvasWidth(){return canvasWidth;}
    public int getCanvasHeight(){return canvasHeight;}


    private class AlgoCanvas extends JPanel{

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);//传入g

            g.drawOval(50, 50, 300, 300);//绘制一个圆形
        }

        @Override//覆盖
        public Dimension getPreferredSize(){
            return new Dimension(canvasWidth, canvasHeight);//返回画布大小
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41264674/article/details/80702048