繁体   English   中英

Java,扩展类或实例化时的StackOverflowError

[英]Java, StackOverflowError when extending a class, or instantiating

好的,起初, 我知道为什么会收到此错误,但只是不知道如何解决。

我有几个类,一个主类,一个布局类和一个ButtonClick类。

问题出在buttonClick类中:在布局类中有一些必须在buttonClick类中使用的变量。

这是我的Layout类:

public class Layout extends JPanel {
    public JButton BTN_werpen;

    public Layout{
        BTN_werpen = new JButton("Werpen");
        BTN_werpen.setBounds(465, 10, 80, 30);
        BTN_werpen.addActionListener(new WerpButton());
        P_velden.add(BTN_werpen);
    }

当然,这不是完整的课程,但这是您需要了解的所有内容。

我有我的“ WerpButton” actionListner类:

public class WerpButton extends Layout implements ActionListener {
    BTN_werpen.setEnabled(false);
}

同样,这还不是全部,但是当我在这里使用代码时,它已经失败了。 我知道为什么失败:这是因为当Layout类扩展时,构造函数被调用,它将创建一个新对象,该对象触发WerpButton类,然后调用Layout类,依此类推。 它基本上成为一个循环。

现在,我的问题是:

我该如何解决这个问题?

我已经尝试了很多,比如不扩展它,而只是使用Layout layout = new Layout(); 然后在我的代码中使用layout.BTN_werpen ,但是那也不起作用。

public class WerpButton extends Layout

因此,您创建了新的WerpButton()本质上称为new Layout()

public Layout() {
    ...
    BTN_werpen.addActionListener(new WerpButton());
    ...
}

再次调用new WerpButton ...,循环重复


为什么ActionListener的名称为“ Button”? (当然,除非在按钮类本身上实现)。

换句话说,为什么在Layout上实现ActionListener?

您是要扩展JButton而不是Layout吗?

public class WerpButton extends JButton implements ActionListener {
    public WerpButton() {
        this.addActionListener(this);
    }

    @Override
    public void onActionPerformed(ActionEvent e) {
        this.setEnabled(false);
    }
}

此外,如果您有单独的类文件,这将无法正常工作

public class WerpButton extends Layout implements ActionListener {
    BTN_werpen.setEnabled(false); // 'BTN_werpen' can't be resolved. 
}

您可以尝试以其他方式进行操作-布局实现侦听器。 这样,您就不需要严格地处理按钮事件的单独类。

public class Layout extends JPanel implements ActionListener {
    public JButton BTN_werpen;

    public Layout() {
        BTN_werpen = new JButton("Werpen");
        BTN_werpen.setBounds(465, 10, 80, 30);
        BTN_werpen.addActionListener(this);
        P_velden.add(BTN_werpen);
    }

    @Override
    public void onActionPerformed(ActionEvent e) {
        if (e.getSource() == BTN_werpen) {
            // handle click
            BTN_werpen.setEnabled(false);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM