title: How to implement ActionListener using an outer class?
body: <p>When I implement ActionListener as an inner class of the registered listener class then it works fine but when I try to do that outside of the registered class, i.e., outer class, then the button action does not work.  </p>
  
  <p>Can anyone explain me why? Or any suggestion to implement ActionListener as an outer class? </p>
  
  <p>The code is below. Thanks in advance. </p>
  
  <pre><code>// MainMethod.java
  
  import java.awt.Dimension;
  import java.awt.Toolkit;
  
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  
  public class MainMethod
  {
    public static void main(String[] args)
    {
      Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
      JFrame frame = new Framework("Tic Tac Toe", size.width / 4,
          size.height / 3, 950, size.height / 8);
  
      JPanel panel = new ButtonPanel();
  
      frame.getContentPane().add(panel);
      frame.setVisible(true);
    }
  }
  
  
  // ButtonPanel.java
  import java.awt.Color;
  import java.awt.GridLayout;
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  
  import javax.swing.JButton;
  import javax.swing.JPanel;
  import javax.swing.border.Border;
  import javax.swing.border.LineBorder;
  
  public class ButtonPanel extends JPanel
  {
    private static final long serialVersionUID = -4829885180501818987L;
    JButton buttons[] = new JButton[9];
  
    ButtonPanel()
    {
  
      String name[] = { "button1", "button2", "button3", "button4", "button5",
          "button6", "button7", "button8", "button9" };
  
      Border lineBorder = new LineBorder(Color.black, 2);
      GridLayout panelLayout = new GridLayout(3, 3);
      setLayout(panelLayout);
  
      for (int i = 0; i &lt; name.length; i++)
      {
        buttons[i] = new JButton(name[i]);
        buttons[i].setBackground(Color.white);
        buttons[i].setBorder(lineBorder);
        buttons[i].addActionListener(new ButtonActionListener());
        add(buttons[i]);
      }
    }
  
    // Inner class implementation
    class ButtonActionListener implements ActionListener
    {
      public void actionPerformed(ActionEvent ae)
      {
  
        if (ae.getActionCommand().equals("button1"))
        {
          buttons[0].setText("X");
        }
      }
    }
  }
  </code></pre>
  
  <p>And following is the outer class implementation which doesn't work when used:</p>
  
  <pre><code>// ButtonActionListener.java
  import java.awt.event.ActionEvent;
  import java.awt.event.ActionListener;
  
  class ButtonActionListener implements ActionListener
  {
    public void actionPerformed(ActionEvent ae)
    {
      ButtonPanel buttonPanel = new ButtonPanel();
      if (ae.getActionCommand() == "button1")
      {
        buttonPanel.buttons[0].setText("X");
      }
    }
  }
  </code></pre>