I have a class Game and an array of buttons buts, i want to call function on the Game class fun(i,j) when any buts[i][j] is clicked , i tried like this:
buts = new JButton[Setting.length][Setting.width];
Game game = new Game(setting);
int hgap = 4, vgap = 4;
panel = new JPanel(new GridLayout(Setting.length, Setting.width, hgap, vgap));
for (int i = 0; i < Setting.length; i++) {
for (int j = 0; j < Setting.width; j++) {
//JButton btn = new JButton();
buts[i][j] = new JButton();
buts[i][j].setText(String.valueOf(j));
setColor(buts[i][j], Game.cells[i][j].getColor());
buts[i][j].addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonActionPerformed(evt);
}
});
panel.add(buts[i][j]);
}
}
private void buttonActionPerformed(ActionEvent evt) {
}
but how can i send i,j to the function buttonActionPerformed ?
You could use a concrete Action for each
JButtonand pass in the valuesi&jinto the constructor of the class.Adding:
The
Actionimplementation:And: