在swing paint方法中使用object属性

时间:2018-01-15 16:03:26

标签: java swing

我一直在尝试使用swing创建一个迷宫。

现在,我只是想用线条创建一个10x10网格,这些线条都在我的细胞周围(40x40平方,来自“w”)。我正在尝试根据boolean[] walls标签创建广场的每一行(walls[0]为顶部,walls[1]为正确,walls[2]为底部,walls[3]是的。) 如果值为true,那么我们有一堵墙,如果没有,则通道打开,此侧没有线。
我正在使用ArrayList<Cell>来收集网格的不同单元格。

所有这一切都在起作用(似乎),但我遇到了一个问题 实际上,我想在paintComponent(Graphics g)中使用我的对象(Cell)属性来制作单元格的自定义尺寸 但是,我真的不知道该怎么做。我试图将我的Cell class分开并为我的图形界面做另一个类,但它也没有成功。

public class Cell {
    int i,j;
    int w = 40;
    ArrayList<Cell> grid = new ArrayList<Cell>();
    boolean[] walls = new boolean[4];
    boolean visited;


    public Cell () {
        this.setup();
    }


    public Cell(int i, int j) {
        this.i = i;
        this.j = j;

        this.walls[0] = true;
        this.walls[1] = true;
        this.walls[2] = true;
        this.walls[3] = true;

        this.visited = false;
    }

    public int getI() {
        return i;
    }

    public int getJ() {
        return j;
    }

    public void setup() {
        JFrame f = new JFrame("Maze");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400, 400);
        f.setVisible(true);
        JPanel panel = new JPanel();
        f.getContentPane().add(panel);

        int cols = (int) f.getWidth()/w;
        int rows = (int) f.getHeight()/w;

        for (int j = 0; j < rows; j++)
        {
            for (int i = 0; i < cols; i++)
            {
                Cell cell = new Cell(i,j);
                grid.add(cell);
            }
        }
    }

    public void paintComponent(Graphics g) { 

        int x = i*w;
        int y = j*w;

        g.setColor(Color.black);

        if (this.walls[0])
            g.drawLine(x    , y    , x + w, y    );

        if (this.walls[1])
            g.drawLine(x + w, y    , x + w, y + w);

        if (this.walls[2])
            g.drawLine(x + w, y + w, x    , y + w);

        if (this.walls[3])
            g.drawLine(x    , y + w, x    , y    );
    }



    public static void main(String[] args) {
        new Cell();
    }
}

1 个答案:

答案 0 :(得分:0)

您不能只将paintComponent(...)方法添加到类中,并期望调用该方法。

要进行自定义绘制,请覆盖paintComponent()的{​​{1}}方法。所以你需要一个自定义面板。该面板将包含JPanelArrayList个对象,并在Cell方法中迭代每个Cell对象并绘制它。

首先,您需要首先阅读Custom Painting上的Swing教程中的部分,以了解绘制单个对象的基础知识。

一旦您了解,您可以查看Custom Painting Approaches,其中显示了如何从对象列表中绘制。