承接用法一,可以把实现接口的监听器类单独放在外面,但是这时候有个问题,当处理接口的方法要改变框架里组件的状态时,需要在构建监听器是传入这个组件的引用作为参数。
上例做如下修改:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonFrame extends JFrame
{ //继承框架
private JPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
ColorListener yellowListener,blueListener, redListener;//声明监听器,作为一个成员变量
public ButtonFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// 创建按钮对象
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
buttonPanel = new JPanel();
// 添加按钮到画板
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
add(buttonPanel);
// 创建按钮监听器,要传入组件的引用
yellowListener = new ColorListener(Color.YELLOW, buttonPanel);
blueListener = new ColorListener(Color.BLUE, buttonPanel);
redListener = new ColorListener(Color.RED, buttonPanel);
// 为每个按钮设置监听器
yellowButton.addActionListener(yellowListener);
blueButton.addActionListener(blueListener);
redButton.addActionListener(redListener);
}
}
//监听器单独作为一个外部类
class ColorListener implements ActionListener
{//实现监听接口
private Color backgroundColor;
private JPanel panel;
public ColorListener(Color c,JPanel p) {//单独作为一个类时要传入要修改组件的引用
backgroundColor = c;
panel=p;
}
public void actionPerformed(ActionEvent event) {
panel.setBackground(backgroundColor);//要把引用传给监听器类
}
}