I have a class called cell, which extends JButton. Then I have 16 Jbuttons in a gridlayout(4,4,3,3). Is it possible to have every cell keep track of its position in the gridlayout(I will need to know if one clicked JButton is near to another specific JButton).
-
What kind of buttons are these? Are they array based buttons? Cause you can calculate the position of the button in the grid layout based on the array position of the button. Or you can create custom JButtons so that they store the position within them if the 16 buttons are not in any array. – Aman Agnihotri Mar 31 '14 at 13:14
-
I did that, I stored them in a List, but the problem, (this buttons and gridlaoyout is a slide puzzle game) i cant move the button to left bottom after it being moved for the first time, so i thougt i would try another way where every button keep track of its position – UserFuser Mar 31 '14 at 13:21
2 Answers
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);
}
}

- 5,187
- 31
- 50
-
How to I assign their gridx and gridy position from the main class which creates the gridlayout? – UserFuser Mar 31 '14 at 13:26
-
I stored them in a List, but the problem, (this buttons and gridlaoyout is a slide puzzle game) i cant move the button to left bottom after it being moved for the first time, so i thougt i would try another way where every button keep track of its position
change Icon for JButton from added ActionListener
I'd be use
JToggleButton
withItemListener
for puzzle game
-
@user3079108: See also this related [example](http://stackoverflow.com/a/7706684/230513). – trashgod Mar 31 '14 at 16:00