动态规模Sierpinski三角形

时间:2015-02-19 19:52:22

标签: java recursion graphics paintcomponent

对于课程,我被要求制作一个Sierpinski三角抽屉,当用户改变窗口大小时,它会动态重新缩放,通过递归细分面板的方形区域直到int为1x1像素,然后着色该像素。我认为我几乎就在那里,但由于我对面向对象编程的理解充其量是模糊的,所以我并不完全清楚如何实际绘制单个像素。每次调整窗口大小时,paintComponent方法都会被调用吗?因此我需要它来调用sierMaker并创建三角形,但是如果sierMaker然后调用paintsComponent来绘制像素而不是它进入无限循环?我毫不怀疑我在这里遗漏了一些明显的东西,我会很感激帮助弄清楚我的错误是什么。对新手有点怜悯吗?

    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.util.*;

    public class Triangle extends JPanel {

        public int getsize(){
            int wi = this.getWidth();
            int he = this.getHeight();
            int size = 0;

            if (wi <= he) {
                size = wi;
            } else {
                size = he; }

            return size;
        }

        public void sierMaker(int x, int y, int side) {


                //if is 1x1, draw it, else subdivide(WIP)
                if (side == 1) {
                    //create rectangle object (x,y,side,side), and pass it to paintComponent. This is where I need help.


                } else {
                //was too large, break into 3 portions and check again
                    sierMaker(x/2, y, side/2);
                    sierMaker(x,y/2,side/2);
                    sierMaker(x/2,y/2,side/2);
                }   
        }

        //paintComponent method to draw individual pixels once input sqare is subdived into small enough portions by recursion
            public void paintComponent(Graphics g) {

                sierMaker(0,0,getsize());
            }

        public static void main(String[] args) {

            //set initial size of panel to monitor resolution
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

            //initalize JFrame
            JFrame display = new JFrame();
            display.setTitle("Sierpinski Triangles");
            display.setBounds(0,0,screenSize.width, screenSize.height);
            display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            Triangle panel = new Triangle();
            display.add(panel);
            display.setVisible(true);
        }
    }

0 个答案:

没有答案