我正在尝试创建一个由单元格组成的 10 x 10 网格的 Java 游戏。
网格看起来像这样:
public class Grid extends JPanel implements MouseListener {
public static final int GRID_SIZE = 10;
public Grid() {
setPreferredSize(new Dimension(300, 300));
setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
for (int x = 0; x < GRID_SIZE; x++)
for (int y = 0; y < GRID_SIZE; y++)
add(new Cell(x, y));
addMouseListener(this);
}
// All Mouse Listener methods are in here.
Cell 类如下所示:
public class Cell extends JPanel {
public static final int CELL_SIZE = 1;
private int xPos;
private int yPos;
public Cell (int x, int y) {
xPos = x;
yPos = y;
setOpaque(true);
setBorder(BorderFactory.createBevelBorder(CELL_SIZE));
setBackground(new Color(105, 120, 105));
setPreferredSize(new Dimension(CELL_SIZE, CELL_SIZE));
}
// Getter methods for x and y.
我的问题是我现在正在尝试在 Grid 类中实现 MouseListeners。我意识到,虽然我可以返回网格的 X 和 Y 坐标,但我似乎无法操纵单元格本身。
我假设这是因为当我在 Grid 中创建它们时,我创建了 100 个没有标识符的随机单元格,因此我无法直接访问它们。
有人可以给我这方面的建议吗?我是否需要彻底修改我的代码和创建单元格的方式?我是否非常愚蠢并且错过了访问它们的明显方式?
谢谢
您可以使用适配器模式,如下所示。这样,您可以将侦听器单独添加到每个网格单元,但仍然处理来自Grid
.
注意Grid
不再实施MouseListener
,现在由细胞处理。
public class Grid extends JPanel {
public static final int GRID_SIZE = 10;
public Grid() {
setPreferredSize(new Dimension(300, 300));
setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
for (int x = 0; x < GRID_SIZE; x++) {
for (int y = 0; y < GRID_SIZE; y++) {
final Cell cell = new Cell(x, y);
add(cell);
cell.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
click(e, cell);
}
// other mouse listener functions
});
}
}
}
public void click(MouseEvent e, Cell cell) {
// handle the event, for instance
cell.setBackground(Color.blue);
}
// handlers for the other mouse events
}
子类可以将其重写为:
public class EnemyGrid extends Grid {
public void click(MouseEvent e, Cell cell) {
cell.setBackground(Color.red);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)