You could simply create a class extending JButton
and adding two fields for the position in the grid. Create a new constructor (or setters) that assign values to theses fields, and two simple getters that will return them.
Example :
class MyJButton extends JButton {
private int gridx;
private int gridy;
public MyJButton(String label, int gridx, int gridy) {
super(label);
this.gridx = gridx;
this.gridy = gridy;
}
public int getGridx() {
return gridx;
}
public int getGridy() {
return gridy;
}
}
You can assign these gridx
,gridy
values when you build the GUI. For example, the following creates 16 buttons, labelled with their position in the grid :
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
MyJButton btn = new MyJButton(i + "," + j, i, j);
//Configure your button here...
panel.add(btn);
}
}