Question

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

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top