import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ManyEars extends JFrame{
  private JButton button;
  private JTextArea textArea;
  private JScrollPane panel;

  public ManyEars (String title){
    super(title);

    button=new JButton("test");
    textArea=new JTextArea(20,20);
    //在垂直方向总是显示滚动条，在水平方向只有当需要的时候才显示滚动条
    panel=new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                               JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);


    // JButton注册5个ActionListener监听器
    for(int i=0;i<5;i++)
      button.addActionListener(new ListenerA());
    
    // JButton注册1个MouseListener监听器
    button.addMouseListener(new ListenerB());

    add(button,BorderLayout.NORTH);
    add(panel,BorderLayout.CENTER);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
  }

  private void print(String str){
    textArea.setText(textArea.getText()+str+"\n");
  }

  private static int count;  //统计ListenerA的实例的数目
  class ListenerA implements ActionListener{
    private int serialNumber;
    public ListenerA(){count++;serialNumber=count;}
    public void actionPerformed(ActionEvent evt){
      print("ListenerA"+serialNumber+" receives ActionEvent.");
     }
  }

  class ListenerB extends MouseAdapter{
    public void mousePressed(MouseEvent evt){
      //获得所有的向JButton注册的ActionListener
      ActionListener[] listeners=(ActionListener[])button.getListeners(ActionListener.class);
      print("ListenerB receives MouseEvent.");
      //从JButton中注销一个ActionListener
      if(listeners.length>0)button.removeActionListener(listeners[0]);
      print("There are "+(listeners.length>0?listeners.length-1:0)+" ListenerA.");

    }
  }

  public static void main(String args[]){
    new ManyEars("Hello");
  }
}


/****************************************************
 * 作者：孙卫琴                                     *
 * 来源：<<Java面向对象编程>>                       *
 * 技术支持网址：www.javathinker.net                *
 ***************************************************/
