如何使用MouseListener查找网格中的特定单元格

时间:2013-04-24 13:11:19

标签: 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.

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个没有标识符的随机单元格,因此我无法直接访问它们。

有人能就此提出建议吗?我是否需要彻底检查我的代码以及创建单元格的方式?我是非常愚蠢的,并且错过了一种明显的访问方式吗? 感谢

3 个答案:

答案 0 :(得分:2)

您可以使用适配器模式,如下所示。这样,您可以单独将侦听器添加到每个网格单元格,但仍然可以处理来自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);
    }
}

答案 1 :(得分:2)

答案 2 :(得分:1)

最明显的方法是将MouseListener移到Cell班级上。

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