how to get the row and column of a component
I am using gridlayout to display a 9x9 grid of jbuttons and jlabels, representing a futoshiki puzzle (thanks Fubarable). When you click a button it changes values from 0 to 5. I have another class (Futoshiki) that holds all the data of the puzzle and the GUI class is responsible only for displaying that data. Upon clicking a button at a specific row and column i want to set the value of the same cell in the Futoshiki class to the whatever text is in the button. I know i can do this by writing a separate listener class for each button and set the row and the column manually(as in the code below) but i was wondering if there is a more efficient way of doing this. Is it possible to get the row and the column of a specific component(button) and return it as an int value that can be passed on to another method?
Here is my code:
the button
Code:
panelGrid.setLayout(new GridLayout(0, 9));
JButton b00 = new JButton(" ");
ActionListener ac = new Counter(b00);
b00.addActionListener(new Counter(b00));
panelGrid.add(b00);
The listener class
Code:
public class Counter implements ActionListener
{
private int count;
private JButton button;
private int row;
private int col;
public Counter(JButton b)
{
button = b;
// here i am doing this manually
row = 0;
col = 0;
}
public void actionPerformed(ActionEvent e)
{
count++;
if (count > 5) {
count = 0;
}
button.setText(""+count);
Futoshiki f = new Futoshiki();
Futoshiki.setSquare(row, col, count);
System.out.println("CLICKED "+count+" TIMES");
}
}
The setSquare method
Code:
public static void setSquare(int row, int column, int val)
{
squares[row][column] = new FilledSquare(val);
}
Thank you in advance for your time.