1

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){}


}

}
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Daviepark
  • 65
  • 1
  • 11

2 Answers2

2

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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

You will want to iterate through your JLabel array in a for loop to find the index number of the label that was pressed. Then use that index number and some simple math (mod and int division) using the grid dimensions to figure out the proper grid position.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373