You could assign one instance of an ActionListener
to all buttons, roughly like this:
class ButtonActionListener extends ActionListener {
private JButton previousButton = null;
@Override
public void actionPerformed(ActionEvent e){
JButton currentButton = (JButton)e.getSource();
if (previousButton == null) {
previousButton = currentButton;
return;
}
Icon previousIcon = previousButton.getIcon();
Icon currentIcon = currentButton.getIcon();
currentButton.setIcon(previousIcon);
previousButton.setIcon(currentIcon);
previousButton = null;
}
}
Where the buttons are created:
ActionListener buttonActionListener = new ButtonActionListener();
for (int i = 0; i<buttons.length; i++) {
...
buttons[i] = new JButton(...);
buttons[i].addActionListener(buttonActionListener);
}
But I'd strongly recommend to think about an appropriate structure for your game that is closer to the Model-View-Controller pattern: You should store your game state in a dedicated class, and not only in form of the icons that they show. Whatever you intended to achieve by setting the "actionCommand" of the buttons will most likely not work properly as long as you do not have an appropriate representation of the game state!