使用GridLayout更改JPanel中的组件

时间:2015-08-04 07:05:59

标签: java swing jpanel grid-layout

这是以下代码。

import javax.swing.*;

import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;

public class Grid extends JPanel {

    private static final long serialVersionUID = 1L;

    private ArrayList<Cell> cells;
    private int width = 20;
    private int height = 20;

    public Grid() {
        cells = new ArrayList<Cell>();
    }

    public void drawGrid() {
        this.setLayout(new GridLayout(width, height, 5, 5));
        this.setBackground(Color.RED);

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                Cell cell = new Cell(i, j);
                cells.add(cell);
            }
        }
        for (Cell c : cells) {
            this.add(c);
        }

    }

    public ArrayList<Cell> getCells() {
        return cells;
    }

    public void setCells(ArrayList<Cell> cells) {
        this.cells = cells;
    }

    public void changeCell(Cell c) {
        for (Cell cell : cells) {
            if (cell.getx() == c.getx() && cell.gety() == c.gety()) {
                cell = c;

                /*
                System.out.println(c.getx() + " " + c.gety()
                                    + c.getBackground().toString());
                                    */

            }
        }
    }

此代码中的问题可在changeCell(Cell c)中找到,我想将此新单元格添加到JPanel单元格中。目前,在网格中添加单元格的代码行是在每个循环下面找到的增强for循环,以绘制网格(this.add(c))。

我无法将changeCell(Cell c)方法中找到的传递参数添加/更新到当前JPannel中找到的单元格。我需要做的就是更新ArrayList,以便JPanel上的Cells对应于ArrayList中的单元格。

1 个答案:

答案 0 :(得分:1)

您正在更改模型(ArrayList<Cell>)但未对其视图进行任何更改(您的网格JPanel)。 尝试这样的事情:

public void changeCell(Cell c) {
    this.removeAll(); //erase everything from your JPanel
    this.revalidate; this.repaint();//I always do these steps after I modify my JPanel
    for (Cell cell : cells) {
        if (cell.getx() == c.getx() && cell.gety() == c.gety()) {
              this.add(c);
        else this.add(cell);
    }
}

简而言之,从面板中删除所有内容并再次添加单元格,但是当您找到要更改的单元格时,请添加该单元格而不是另一个单元格。

或者,更好的是,您应该使用Model-View-Controller pattern,其中您的模型是您的ArrayList,您的视图是您的Grid JPanel,您的Controller是JApplet \ JFrame或其他创建视图和模型的东西。

让我知道。再见!

相关问题