so im making a chess game but only with the knight.
this is the method for moving the knight
public void caballo(final int row, final int column) {
Like nachokk said, you should use: component.removeActionListener(theActionListenerYouWantToRemove)
Here is how you can use it in your e
method:
public ActionListener e(final int row, final int column,
final JButton current) {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
current.setIcon(null);
if (tienebotton(row + 2, column + 1)) {
if (e.getSource() == mesa[row + 2][column + 1]) {
caballo(row + 2, column + 1);
}
}
if (tienebotton(row + 2, column - 1)) {
if (e.getSource() == mesa[row + 2][column - 1]) {
caballo(row + 2, column - 1);
}
}
if (tienebotton(row - 2, column - 1)) {
if (e.getSource() == mesa[row - 2][column - 1]) {
caballo(row - 2, column - 1);
}
}
if (tienebotton(row - 2, column + 1)) {
if (e.getSource() == mesa[row - 2][column + 1]) {
caballo(row - 2, column + 1);
}
}
if (tienebotton(row + 1, column + 2)) {
if (e.getSource() == mesa[row + 1][column + 2]) {
caballo(row + 1, column + 2);
}
}
if (tienebotton(row - 1, column + 2)) {
if (e.getSource() == mesa[row - 1][column + 2]) {
caballo(row - 1, column + 2);
}
}
if (tienebotton(row + 1, column - 2)) {
if (e.getSource() == mesa[row + 1][column - 2]) {
caballo(row + 1, column - 2);
}
}
if (tienebotton(row - 1, column - 2)) {
if (e.getSource() == mesa[row - 1][column - 2]) {
caballo(row - 1, column - 2);
}
}
((AbstractButton) e.getSource()).setEnabled(false);
((AbstractButton) e.getSource()).removeActionListener(this);
}
};
}
I see that you are new to Java, you'll notice that I have slightly modified your e method to only call current.setIcon(null);
and ((AbstractButton) e.getSource()).setEnabled(false);
I have also made sure that the remove action listener is only called once aswell, you should look to avoid writing duplicate code as much as possible.