import java.awt.*;
import java.awt.event.*;
public class TestFrame implements ActionListener
{
private Frame f = new Frame("aframe");
private void init()
{
Button btn = new Button("quit");
//btn.addActionListener(this);//我认为应该这样
btn.addActionListener(new TestFrame());//为什么这样也可以??
f.add(btn);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
f.setVisible(false);
f.dispose();
System.exit(0);
}
public static void main(String [] args)
{
TestFrame tf = new TestFrame();
tf.init();

}
}

解决方案 »

  1.   

    因为无论你将"this"还是"new TestFrame()"作为btn的事件监听器注册,处理方法里都调用了System.exit(0);,终止当前正在运行的 Java 虚拟机。
      

  2.   

    这里的this其实就是指向TestFrame对象的
      

  3.   

    public interface ActionListenerextends EventListenerThe listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked. 实现了ActionListener接口的类的实例都可以被注册为button的事件监听者
      

  4.   

    btn.addActionListener(new   TestFrame());//为什么这样也可以?? 因为class TestFrame 继承了 ActionListener(说明TestFrame是一个ActionListener的实例)
    然后addxxxxListener方法自动转型了但有时候这样不好 使用事件的对象  和实现事件的对象 不在一个范围中(他们没有共享的东西)
    比如你这个按钮的处理事件想保存窗口上的文本 但是事件的实现对象 和按钮这个对象不在一个实例对象中
    结果除非传如具体值 否则事件的实现对象怎么会知道 按钮所在窗体的文本框的值应该去了解下匿名类