How to get position(I mean row and column) of the clicked button with gridlayout?
public void init(final Container pane) {
JPanel controls = new JPanel();
In this case, you don't even have to search for the indices, because you know them when the button is created:
for (int i = 0; i < puzzle.getSize(); i++) {
int k = puzzle.getListItem(i);
if (k == puzzle.getEmptyFlag())
controls.add(new JLabel(""));
else {
JButton jb = new JButton(String.valueOf(k));
final int rowIndex = i / size;
final int columnIndex = i % size;
// Using an ActionListener, as Hovercraft Full Of Eels already told you:
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("rowIndex "+rowIndex+" columnIndex "+columnIndex);
}
});
controls.add(jb);
}
}