title: AWT: swap button objects
body: <p>Is it possible to swap 2 button references in java awt?</p>
  
  <p>If 2 buttons are swapped, their name should be updated in the frame automatically. But even calling button.repaint () after making the swap does not make any visible change.</p>
  
  <p>Changing a buttons name with button.setLabel (" ") is not a sufficient solution.</p>
  
  <p>Events of a button get caught by a ActionListener. See cast from actionEvent to Button object.. </p>
  
  <pre><code>import java.awt.Button;
  import java.awt.Frame;
  import java.awt.GridLayout;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  import java.util.ArrayList;
  import java.util.List;
  
  public class Test extends Frame {
      private static final long serialVersionUID = 1L;
      private List&lt;Button&gt; buttons = new ArrayList&lt;&gt;();
      private List&lt;Button&gt; buttonsToSwap = new ArrayList&lt;&gt;();
  
      public Test() {
          setLayout(new GridLayout(3, 3));
          initButtons();
          addButtons();
          setSize(400, 400);
          setVisible(true);
      }
  
      private void initButtons() {
          for (int i = 0; i &lt; 9; i++) {
              buttons.add(new Button(Integer.toString(i + 1)));
          }
      }
  
      private void addButtons() {
          for (Button b : buttons) {
              add(b);
              b.addActionListener(new MyActionListener());
          }
      }
  
      private class MyActionListener implements ActionListener {
          @Override
          public void actionPerformed(ActionEvent e) {
              buttonsToSwap.add((Button) e.getSource());
              if (buttonsToSwap.size() &gt;= 2) {
                  buttonSwap(buttonsToSwap.get(0), buttonsToSwap.get(1));
                  buttonsToSwap.clear();
              }
          }
  
          private void buttonSwap(Button b1, Button b2) {
              Button temp = b1;
              b1 = b2;
              b2 = temp;
              // button.repaint()???
          }
      }
  
      public static void main(String[] args) {
          new Test();
      }
  }
  </code></pre>