如何使用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. 

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); } } 
  • 使用put / getClientProperty

  • 您可以使用其他附加参数来多次使用此方法

  • 关于如何确定网格中单击的JButton的示例,与JPanelMouse(Xxx)Listener相同的逻辑

  • 覆盖getPreferredSize(new Dimension(x, y))而不是setPreferredSize(new Dimension(CELL_SIZE, CELL_SIZE));

最明显的方法是在Cell类本身上移动MouseListener

我能想到的第二个选项是使用java.awt.Container.getComponentAt(int, int)