java监听器用法(二):窗口监听器

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonFrame extends JFrame implements ActionListener{//窗口直接实现了监听接口,整个窗口作监听器
   private static final long serialVersionUID = 1L;
   private JPanel buttonPanel;
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 200;
   JButton  yellowButton ,blueButton,redButton;
   public ButtonFrame()
   {      
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
      // 建立按钮对象
      yellowButton = new JButton("Yellow");
      blueButton   = new JButton("Blue");
      redButton    = new JButton("Red");
      buttonPanel = new JPanel();
      // 添加按钮到画板
      buttonPanel.add(yellowButton);
      buttonPanel.add(blueButton);
      buttonPanel.add(redButton);    
      add(buttonPanel);
      // 为每一个按钮设置监听器,这里要用this,表示窗口自己
      yellowButton.addActionListener(this);
      blueButton.addActionListener(this);
      redButton.addActionListener(this);
   }
   @Override
   public void actionPerformed(ActionEvent e) {
    // //窗口作监听器,要使用e.getSource()方法判断触发事件的事件源
    if(e.getSource()==yellowButton)
         buttonPanel.setBackground(Color.YELLOW);
    if(e.getSource()==blueButton)
        buttonPanel.setBackground(Color.BLUE);
    if(e.getSource()==redButton)
        buttonPanel.setBackground(Color.RED);     
    }
}