import java.awt.*;
import java.awt.event.*;;
public class TextActionEvent{
public static void main(String[]args){

Frame f=new Frame("My feist");

Button b1=new Button("start");

Monitor kk=new Monitor();

b1.addActionListener(kk);

f.setSize(110,100);
f.setLayout(new FlowLayout());
f.setBackground(Color.black);
f.add(b1);
f.setVisible(true);
}

}
class Monitor implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println("aa");

}

}

在这代码中怎么都不明白 public void actionPerformed(ActionEvent e) 的必要性。
书上说是封装方法传递给e。但是为什么不能直接访问下面的 System.out.println("aa");? 谢谢指教

解决方案 »

  1.   

    刚给你写的一个button事件触发的代码,目的就是点下button,就变色。import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class Test extends JFrame{
    private JPanel panel;
    private JButton button;
    private static int count = 1;

    public Test(){
    super("Test Set Button Color");

    panel = new JPanel();
    button = new JButton("Change Color");

    panel.setLayout(new BorderLayout()); button.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    if (count%2 == 1)
    button.setBackground(Color.green);
    else
    button.setBackground(Color.red);

    count ++;
    }
    }
    );

    panel.add(button, BorderLayout.CENTER);

    setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);

    setSize(250, 100);
    setVisible(true);
    }

    public static void main(String args[]){ 
        new Test();
    }
    }
      

  2.   

    触发时掉用actionPerformed()方法
    然后打印。
      

  3.   

    public void actionPerformed(ActionEvent e){
    。。
    }
    有任何事件时(例如键盘事件),就生成一个ActionEvent对象,并调用actionPerformed()方法
    b1.addActionListener(kk); 
    因为你前面已经有这句了,就是注册了此事件监听器。然后调用kk的actionPerformed()方法,产生ActionEvent对象。
      

  4.   

    点击按钮触发事件  该按钮是个事件源
    public void actionPerformed(ActionEvent e){ 
     
    }  是个监听器b1.addActionListener(kk);给按钮绑定了一个监听器
      

  5.   

    楼上讲得很清楚了 button 添加了一个监听器点击button就触发事件然后执行
    public void actionPerformed(ActionEvent e){ }里边内容你可以直接让本类implement ActionListener
    然后重写方法并在类的构造器中 添加按钮的监听对象this