//  内部类-action传外部类给内部类import java.awt.*;
import java.awt.event.*;public class bb 
{
public static void main(String args[])
    {
     Test t = new Test("testing");
     t.setSize(200, 200);
     t.setVisible(true);
    }
}class Test extends Frame
{
Button button;

public Test(String str)
{
     super(str);
    
     button = new Button("well");
     this.add(button, BorderLayout.NORTH);
     TestListener handl = new TestListener(this);  //  this -> test.setBackground(Color.cyan);
     button.addActionListener(handl);    
    } private class TestListener implements ActionListener
{
Test test;

public TestListener(Test test1)  // this = Frame
{
this.test = test1;
}

public void actionPerformed(ActionEvent e)  // 为什么这段程序会被执行, 在Test中只调用了构造函数呀?
    {// 当一个动作发生时该方法被调用。相应Button按下事件.
button.setBackground(Color.red);
test.setBackground(Color.cyan);  // test = Frame str
}

}//TestListener
    
}

解决方案 »

  1.   

    public void actionPerformed(ActionEvent e)  是否在new前被执行
      

  2.   

    public void actionPerformed(ActionEvent e)  是否在new前被执行
    ------------------------------
    不是。new 只是初始化一个对象,只执行构造函数。private class TestListener implements ActionListener 
    //内部类TestListener 继承了监听器类ActionListener,以便用于按钮Button 类的对象。Button button = new ...
    //button 是Button 类的一个实例对象,每个Button 对象都要实现对应的监听器,目的是在该对象按钮被按下后,执行相应的动作(即,执行该按钮所加入的 ActionListener类对象的 actionPerformed(..)方法)。button.addActionListener(handl);
    //则是在该 button对象中加入 ActionListener类对象handl。如前所说,只要该button 被按下,就会被监听器 handl捕获到,并执行 handl.actionPerformed(...)方法。至于为什么会被捕获到,就得看 监听器ActionListener类的原代码咯。
      

  3.   

    不是很明白楼主的意思。
    楼主指的是public void actionPerformed(ActionEvent e)为什么会被执行。
    还是说public void actionPerformed(ActionEvent e)为什么启动的时候会被执行?public void actionPerformed(ActionEvent e)只有在点击了button之后才会被执行的。
    因为你注册了事件:button.addActionListener(handl);