java - Clickable JLabels in a grid X and Y coordinates? -
i trying implement small grid of boxes using jlabels in grid layout. idea when click on specific box x , y coordinates dispalyed on console window. have far , believe there, when click on each box incorrect numbers appearing in window. instance when click on box should read (0,0) gives me 16,17...??? 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]; (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()); } (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){} } }
you want iterate through jlabel array in loop find index number of label pressed. use index number , simple math (mod , int division) using grid dimensions figure out proper grid position.
Comments
Post a Comment