Pregunta

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

¿Fue útil?

Solución

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

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top