我正在做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);
}
}现在单元格定义为
public class Cell extends JPanel implements MouseListener{
}当单元格被单击时,将调用单元格的方法MouseClicked,但类PlayConnect不会调用该方法。我不知道为什么。我确实尝试过将gridPanel类型更改为JLayeredPane,但也没有任何帮助。
发布于 2015-05-06 04:28:12
您没有将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);
}发布于 2015-05-06 04:31:34
找到我的问题了。在循环中添加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);
}https://stackoverflow.com/questions/30062583
复制相似问题