object作为参数传递,为什么我们不能在类中声明它

时间:2013-03-22 19:03:13

标签: java

此代码的问题在于,无论何时运行此代码,都会显示

编译错误 -

“找不到符号:构造函数mywindowadapter(frame1)

location:class mywindowadapter                mywindowadapter mwa = new mywindowadapter()“

import java.awt.*;
import java.awt.event.*;
/*<applet code=frame2 width=500 height=500>
</applet>*/
class frame2 extends Frame
{
    frame2(String title)
    {
        super(title);
        mywindowadapter mwa=new mywindowadapter();
        addWindowListener(mwa);     
    }
    public static void main(String ar[])
    {
        frame1 f=new frame1("my frame");
        f.setVisible(true);
        f.setSize(200,100);

     }
    public void paint(Graphics g)
     {
    g.drawString("hello frame",60,70);
     }
}
class mywindowadapter extends WindowAdapter
{

    mywindowadapter()
    {
        frame2 f=new frame2();  
    }
    public void windowClosing(WindowEvent we)
    {
        f.setVisible(false);
        System.exit(0);
    }
} 

以下代码是上述代码的修正版本。我无法理解前面代码中生成的错误。请帮助!!

import java.awt.*;
import java.awt.event.*;
/*<applet code=frame1 width=500 height=500>
</applet>*/
class frame1 extends Frame
 {
    frame1(String title)
    {
        super(title);
        mywindowadapter mwa=new mywindowadapter(this);
        addWindowListener(mwa);     
    }
    public static void main(String ar[])
    {
        frame1 f=new frame1("my frame");
        f.setVisible(true);
        f.setSize(200,100);

    }
   public void paint(Graphics g)
    {
        g.drawString("hello frame",60,70);
    }
}
class mywindowadapter extends WindowAdapter
{
    frame1 f;
    mywindowadapter(frame1 f)
    {
        this.f=f;   
    }
    public void windowClosing(WindowEvent we)
    {
        f.setVisible(false);
        System.exit(0);
    }
}   

1 个答案:

答案 0 :(得分:0)

因为在frame1的构造函数中,您正在尝试创建一个使用Adapter pattern的适配器实例,并将处理事件委托给适配器frame1,该引用作为参数传递。此适配器由您添加到frame1的侦听器列表的侦听器使用。