java–谢尔宾斯基地毯
本程序将使用递归画出谢尔宾斯基地毯,首先我们将主类继承JFrame类,因为要使用JFrame类生成一个窗体,然后在其中定义一个初始化方法:
public void initUI(){ this.setSize(800,600); this.setDefaultCloseOperation(MyJFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setLayout(new FlowLayout()); this.setVisible(true); //设置可见 }
public void paint(Graphics g) { // TODO Auto-generated method stub super.paint(g); g.drawRect(0, 0, this.getWidth(), this.getHeight()); this.test(g, 0, 0, this.getWidth(), this.getWidth(),4); } private int test(Graphics g, int x, int y, int l, int w, int num) { if (num == 0) { return 1; } int temp = x; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { g.fillRect(x, y, l, w); }else g.drawRect(x, y, l, w); test(g, x, y, l / 3, w / 3, num - 1); x += l; } x = temp; y += w; } return 1; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/231447.html原文链接:https://javaforall.net
