gpt4 book ai didi

java - 将我的 ActionListener 与 GUI 类分开,无法正常工作

转载 作者:行者123 更新时间:2023-12-01 17:17:32 26 4
gpt4 key购买 nike

这就是我的代码一开始的样子:https://gist.github.com/anonymous/8270001
现在我将 ActionListener 删除到一个单独的类中:https://gist.github.com/anonymous/8257038

该程序应该给我一些 UI,但它只是继续运行,没有任何 UI 弹出窗口或错误。

有人告诉我:

In your GUI class constructor, you are creating a new nupuVajutus object, but since nupuVajutus extends the GUI class, when you create a nupuVajutus, you are also inherently calling the GUI class constructor by default, thus creating an infinite loop

如果这确实是问题所在,那么我不得不说我不太擅长,需要一些帮助才能使该程序与分离的类一起工作。

最佳答案

你确实已经得到了答案,虽然你得到的不是无限循环,而是无限递归,最终会导致 StackOverflowError。

发生的情况是这样的:

new GUI() 调用new nupuVajutus()。这将通过调用其构造函数来创建一个新的 nupuVajutus 对象。由于 nupuVajutus 扩展了 GUI,这意味着 nupuVajutus 对象是具有附加功能的 GUI 对象。因此,因为它是一个GUI对象,所以需要调用一个GUI构造函数。 nupuVajutus 构造函数不会显式调用 super 构造函数,因此它会在执行前隐式调用 GUI()(无参数)构造函数。在这个对 GUI() 构造函数的新调用中,遇到了另一个 新的 nupuVajutus() 调用,依此类推,无穷无尽...

在我看来,您需要围绕面向对象编程进行更多研究,特别是子类、继承、对象实例和封装等主题。有plenty of resources available to help you .

将 ActionListener 提取到单独的文件后,您不应更改它来扩展 GUI。它扩展了(就像一个蓝图)而不是实例(就像使用该蓝图构建的东西) - 请记住:您可以创建一个类的多个实例。

以前,“nupuVajutus”ActionListener 是一个内部类,因此它可以访问所有封闭类的字段和方法。现在它不再是一个内部类,它需要传递一个对 GUI 实例的引用,以便它可以访问它的方法。像这样的事情:

public class NupuVajutus implements ActionListener {
private final GUI gui;

public NupuVajutus(GUI gui) {
this.gui = gui;
}

public void actionPerformed(ActionEvent e) {
// The GUI instance can now be accessed through the gui field, for example:
gui.something();
// ...
}
}

GUI() 构造函数中:

NupuVajutus nV = new NupuVajutus(this);

老实说,将 ActionListener 保留为内部类并没有什么问题。如果您永远不会在 GUI 类之外使用该类,那么最好将其保留为内部类。

关于java - 将我的 ActionListener 与 GUI 类分开,无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20970788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com