java - 使用 GridLayout 更改 JPanel 内的组件

标签 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 单元格中。目前,在网格中添加单元格的代码行是在 foreach 循环下方找到的增强型 for 循环,用于绘制网格 (this.add(c))。

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

最佳答案

您正在更改模型 ( ArrayList<Cell> ),但其 View (您的网格 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, View 是 Grid JPanel, Controller 是 JApplet\JFrame 或创建 View 和模型的其他内容。

让我知道。再见!

关于java - 使用 GridLayout 更改 JPanel 内的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31802760/

相关文章:

java - Swing - 使用 JTextfield 输入创建 GridLayout

java - 为我的 Tree CellRenderer 设置背景颜色时出现问题

Java用什么布局管理器把窗口分成两个区域

java - 一帧中的两个不同面板 - Java

java - HBase put [util.List [Put])不起作用

java - 在 Java Rundeck Plugin 中添加对 jar 的依赖

java - 检查 Swing 表单是否不包含空字段

java - 使用 SAAJ 使用经过身份验证的 Web 服务?

java - 同步retrofit中如何获取http响应状态2

java - 在 Swing JPanel 中在边框后面绘制图像