【发布时间】: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