繁体   English   中英

使用GridLayout更改JPanel中的组件

[英]Changing the components inside a JPanel with GridLayout

这是下面的代码。

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循环下方找到的增强的for循环,用于绘制网格( this.add(c) )。

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

您正在更改模型( ArrayList<Cell> ),但对其视图(您的Grid JPanelJPanel任何更改。 尝试这样的事情:

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,控制器是JApplet \\ JFrame或其他创建视图和模型的东西。

让我知道。 再见!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM