【发布时间】:2015-05-08 15:10:49
【问题描述】:
我在分层情况下遇到了 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;
}
【问题讨论】:
标签: java swing grid jpanel mouselistener