GetComponentAt Trouble 问题

GetComponentAt Trouble

我在分层情况下遇到 getcomponentat 问题。我进行了很多研究,发现以下线程实际上是我需要的,但它对我不起作用。我在线程中下载了代码并且它可以工作但是当我在我的项目中实现它时它没有。我可能正在做一些我无法指责的非常愚蠢的错误。

我有一个带有基本面板的 JFrame。我添加了一个 gridPanel(它在其上扩展了 JPanel 并实现了 mouselistner。在网格面板上我添加了单元格(它扩展了 JPanel 并且还实现了 mouselistener)。当我单击任何单元格时,我想知道该单元格在网格,但一切都返回为 0,0。

GridLayout + Mouse Listener

就这样吧。

MAINCLASS 
mainFrame = new JFrame("Connect-4");
basePanel = new JPanel();
gridPanel = new Grid(); //Grid extends JPanel

//GRIDCLASS
public class Grid extends JPanel implements MouseListener {
public Grid(){
    //      setPreferredSize(new Dimension(600,700));;
    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); //Cell Exntends JPANEL
            tempCell.addMouseListener(this);
            gridUI[i][j] = tempCell;
            gridTrack[i][j] = 0;
            add(tempCell);

            int index = i*6 + j;
            cellArray.add(tempCell);

        }

    }
    addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub
    System.out.println("Grid Click");
    Cell clickedCell;
    Boolean filled = false;

    Point mousePoint;

    mousePoint = e.getPoint();
    System.out.println(mousePoint.x + "||" + mousePoint.y);
    clickedCell = (Cell)getComponentAt(mousePoint);


    //      Point mousePoint = MouseInfo.
    int cellIndex;
    cellIndex = Integer.parseInt(clickedCell.getName());
    int cellX = cellIndex / 7;
    int cellY = cellIndex % 7;
}


public class Cell extends JPanel implements MouseListener{

private String status; 
private Color curColor;
private Boolean occupied;
public static Boolean gameOver = false;
public static int player;
public static boolean randPlayer = false;
private Color player1 = Color.BLUE;
private Color player2 = Color.RED;
private static int[][] gridTrack = new int[6][7];
public int row,column;
public static int cellSize = 80;
public Cell(int row_in, int column_in){
    setPreferredSize(new Dimension(cellSize,cellSize));
    setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
    setBackground(Color.GRAY);
    player = 0;
    this.setName(Integer.toString(row_in*6+column_in));
    curColor = Color.WHITE;
    addMouseListener(this);
    occupied = false;
    player = 1;
    row = row_in;
    column = column_in;
    gridTrack[row][column] = 0;
}

当触发监听器时,事件点相对于触发事件的组件。将 MouseListener 添加到 Cell 会导致坐标相对于 Cell - 因此在具有这些坐标的父级 Component 上使用 getComponentAt 将始终return 0,0 处的 Cell 作为事件 Point 的坐标永远不会大于 Cell 的 width/height。

考虑使用 单个 侦听器来处理行为,使用适当的技术获取触发事件的组件:

  1. 给父级添加监听器JPanel- 事件的坐标是相对于父级的。因此使用 getComponentAt 将 return 发生 MouseEvent 的组件
  2. 为每个 Cell 添加一个侦听器,并使用 Cell cell = (Cell)e.getSource() 获取触发事件的 Cell