addActionListener方法上的Stackoverflow异常

时间:2011-12-05 01:11:14

标签: java

我的申请有些问题。我正在尝试使用AWT组件创建一个JButton。主要问题是我有一个例外:在QButton.QButton.addActionListener(QButton.java:83)。     如果我评论//this.addActionListener这一行,一切正常。我的对象是扩展Panel

public class QButton extends Panel implements MouseListener,ActionListener{
    public Label text;
    ImagePanel image;
    ActionListener listener;

    public QButton(String text){
        Label l = new Label(text);
        this.add(l);
        this.text=l;

        this.setLayout(new GridBagLayout());
        this.setBackground(Color.gray);

        TextButtonActions ac1=new TextButtonActions(this);
        this.addMouseListener(ac1);
        this.text.addMouseListener(ac1);
    }

    public QButton(ImagePanel img){
        this.setLayout(new GridLayout());

        this.image=img;        
        this.add(image);

        PictureButtonActions ac2=new PictureButtonActions(this);
        this.image.addMouseListener(ac2);
        }

    public QButton(String text, ImagePanel img){
        this.setBackground(Color.gray);
        this.setLayout(new GridLayout());

        Label l = new Label(text);
        this.add(l);
        this.text=l;

        this.image=img;
        this.add(image);

        TAndPButtonActions ac3=new TAndPButtonActions(this);
        this.image.addMouseListener(ac3);
        this.text.addMouseListener(ac3);
    }

    public void setText(String txt)
    {
        this.text.setText(txt);
    }

    public String getText()
    {
        return(text.getText());
    }

    public void setImage(ImagePanel i)
    {
        this.remove(image);
        this.image=i;

        this.add(i);
        //System.out.println("setImage");
        this.validate();
    }

    public ImagePanel getImage()
    {
        return(image);
    }

    void addActionListener(ActionListener listener)
    {
        this.listener=listener;
        this.addActionListener(listener);
    }
}

2 个答案:

答案 0 :(得分:3)

我不熟悉UI的东西,但是你得到StackOverflowException的原因是因为你的程序试图调用自称的方法。

void addActionListener(ActionListener listener)
   // ^^^^^^^^^^^^^^^^^
{
    this.listener=listener;
    this.addActionListener(listener); // <-- will keep calling itself.
       //^^^^^^^^^^^^^^^^^
}

答案 1 :(得分:3)

也许你想说super.addActionListener(listener);