图层中的Java面板..鼠标事件没有流过

时间:2015-05-05 20:23:45

标签: java mouselistener

我正在研究connect 4程序,我遇到了鼠标事件的问题。这是UI的架构。

public class PlayConnect implements  MouseListener {

mainFrame = new JFrame("Connect-4");
basePanel = new JPanel();
mainFrame.add(basePanel);
gridPanel = new JPanel();
gridPanel.addMouseListener(this);
gridPanel.setLayout(new GridLayout(6, 7));
   for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                Cell tempCell = new Cell(i,j);
                gridUI[i][j] = tempCell;
                gridPanel.add(tempCell);


            }
}

现在Cell定义为

public class Cell extends JPanel implements  MouseListener{
}

当单击单元格而不是类PlayConnect时,将调用Cell的MouseClicked方法。我不知道为什么。我确实尝试将gridPanel的类型更改为JLayeredPane,但它也没有帮助。

2 个答案:

答案 0 :(得分:1)

您没有将gridPanel作为MouseListener添加到您的单元格

        for (int j = 0; j < 7; j++) {
            Cell tempCell = new Cell(i,j);
            gridUI[i][j] = tempCell;
            gridPanel.add(tempCell);
            tempCell.addMouseListener(this);
        }

答案 1 :(得分:0)

发现我的问题。在循环中添加了actionlistner。

for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                Cell tempCell = new Cell(i,j);
                tempCell.addMouseListner(this); // New listener
                gridUI[i][j] = tempCell;
                gridPanel.add(tempCell);


            }
相关问题