import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ButtoIconSwap extends JFrame implements ActionListener {
private int index;
private JButton[] button;
private JLabel label;
public ButtoIconSwap() {
index = -1;
JPanel panel = new JPanel(new GridLayout(1,3));
button = new JButton[3];
for (int i=0; i<button.length; i++) {
button[i] = new JButton();
button[i].addActionListener(this);
//button[i].setIcon(.......);
panel.add(button[i]);
}
this.getContentPane().add(panel, BorderLayout.CENTER);
this.getContentPane().add(label = new JLabel(" Ersten Button selektieren! "), BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
int curIndex = -1;
for (int i=0; i<button.length; i++) {
if (e.getSource().equals(button[i])) {
curIndex = i;
break;
}
}
if(index==-1) {
index = curIndex;
label.setText(" Zweiten Button selektieren! ");
}
else {
swapIcons(index, curIndex);
index = -1;
label.setText(" Ersten Button selektieren! ");
}
}
private void swapIcons(int index1, int index2) {
Icon icon = button[index1].getIcon();
button[index1].setIcon(button[index2].getIcon());
button[index2].setIcon(icon);
}
public static void main(String[] args) {
JFrame frame = new ButtoIconSwap();
frame.setBounds(0, 0, 400, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}