1

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).

splungebob
  • 5,357
  • 2
  • 22
  • 45
UserFuser
  • 110
  • 12
  • 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 Answers2

2

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);
    }
}
cheseaux
  • 5,187
  • 31
  • 50
1

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

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