I am trying to implement a small grid of boxes using JLabels in a Grid Layout. The idea is that when you click on a specific box the X and Y coordinates are dispalyed on the console window. I have this so far and I believe it is almost there, however when I click on each box the incorrect numbers are appearing in the window. For instance when I click on the box that should read (0,0) it gives me 16,17...??? Any help would be great! Thanks.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class GridPanel extends JPanel{
private final int HEIGHT = 7;
private final int WIDTH = 12;
private final int TOTAL_BOXES = HEIGHT * WIDTH;
JLabel box[];
public GridPanel()
{
setLayout(new GridLayout(7,12));
box = new JLabel[TOTAL_BOXES];
for (int x = 0;x<box.length;x++){
box[x] = new JLabel("");
box[x].setOpaque(true);
box[x].setPreferredSize(new Dimension(30,30));
box[x].setBackground(Color.white);
box[x].setBorder(BorderFactory.createLineBorder(Color.black));
box[x].addMouseListener(new mListener());
}
for (int x = 0;x<box.length;x++)
add(box[x]);
}
private class mListener implements MouseListener
{
public void mouseClicked(MouseEvent box)
{
int x = box.getX();
int y = box.getY();
System.out.println(x +"," + y);
}
public void mousePressed (MouseEvent e){}
public void mouseExited (MouseEvent e){}
public void mouseReleased (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
}
}