在分层情况下,我对getcomponentat有问题。我已经做了很多研究,发现了下面的线索,这是我真正需要的,但它对我不起作用。我在线程中下载了代码,它可以工作,但是当我在我的项目中实现它时,它没有工作。我可能做了一些很愚蠢的错误,我不能指手画脚。
我有一个JFrame,它有一个基本面板。我添加了一个gridPanel (它扩展了JPanel并实现了mouselistner )。在网格面板上,我要添加单元格(它扩展了JPanel并实现了mouselistener)。当我单击任何单元格时,我想知道该单元格在网格中的位置,但是一切都返回为0,0。
就这样开始了。
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;
}发布于 2015-05-08 16:08:19
当侦听器被触发时,事件的点相对于触发事件的组件。将MouseListeners添加到Cell中会导致坐标相对于该Cell --因此,在带有这些坐标的父Component上使用getComponentAt将始终在0,0返回Cell,因为事件点的坐标永远不会大于单元格的宽度/高度。
考虑使用单个侦听器来处理行为,使用适当的技术获取触发事件的组件:
JPanel添加侦听器-事件的坐标相对于父事件。因此,使用getComponentAt将返回发生MouseEvent的组件Cell添加一个侦听器,并获取使用Cell cell = (Cell)e.getSource()触发事件的Cell。https://stackoverflow.com/questions/30127150
复制相似问题