【问题标题】:Changing the components inside a JPanel with GridLayout使用 GridLayout 更改 JPanel 中的组件
【发布时间】:2015-08-04 07:05:59
【问题描述】:

这是下面的代码。

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

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

【问题讨论】:

    标签: java swing jpanel grid-layout


    【解决方案1】:

    您正在更改模型 (ArrayList&lt;Cell&gt;),但未对其视图进行更改 (您的网格 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,您的控制器是 JApplet\JFrame 或其他创建视图和模型的东西。

    告诉我。再见!

    【讨论】:

    • 我终于做到了,哦,在场景中使用mvc模型是个好主意,再次感谢!!!
    猜你喜欢
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多