Java,扩展 class 或实例化时出现 StackOverflowError

Java, StackOverflowError when extending a class, or instantiating

好的,一开始,我知道为什么我收到这个错误,但不知道如何解决它。

我有几个 classes,一个主 class,一个布局 class 和一个 buttonClick class。

问题出在 buttonClick class:我的布局 class 中有一些变量,我必须在 buttonClick class 中使用它们 class。

这是我的布局class:

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);
    }

当然,这不是完整的 class,但它是您需要知道的一切。

我有我的 'WerpButton' actionListner class:

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

同样,这还不是全部,但是当我只使用这里的代码时它已经失败了。我知道它失败的原因:那是因为当 Layout class 被扩展时,构造函数被调用,它将创建一个新对象,它触发 WerpButton class 然后调用 Layout class , 等等。它基本上变成了一个循环。

现在,我的问题是:

如何解决这个问题?

我已经尝试了很多, 喜欢不扩展它而只是使用 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 的名称是 anything-"Button"? (当然,除非在按钮 class 本身上实现)。

换句话说,为什么要在 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);
    }
}

此外,如果您有一个单独的 class 文件,这将无法工作

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

您可以尝试另一种方式 - 布局实现侦听器。这样你就不需要单独的 class 来严格处理按钮事件。

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);
        }
    }