And*_*tin 5 java swing jpanel grid-layout mouselistener
我正在尝试创建一个由单元格组成的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.
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
我的问题是我现在正在尝试在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
}
Run Code Online (Sandbox Code Playgroud)
子类可以将其重写为:
public class EnemyGrid extends Grid {
public void click(MouseEvent e, Cell cell) {
cell.setBackground(Color.red);
}
}
Run Code Online (Sandbox Code Playgroud)