java.lang.StackOverflowError between two classes

萝らか妹 提交于 2021-01-29 03:54:45

问题


I'm trying to create a JFrame in one class and adding a JPanel to it in my main class, is this not possible?

This is my Main class

public class Main {

    JPanel p;
    JLabel lbl1;

    public static void main(String[] args) {
        new Main();
    }

    Main() {

        new Window();

        JPanel p = new JPanel();
        JLabel lbl1 = new JLabel("Hello");
        p.add(lbl1);
    }

}

And the Window class


public class Window extends Main {
    Window() {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(p);
    }

}

I get the exception in thread "main" java.lang.StackOverflowError


回答1:


Your Window class extends Main. When you call the constructor of a subclass class, the constructor of the parent class is called first.

In your case, you're calling the Window constructor in your Main constructor. The Window constructor call the Main constructor because of the inheritance, causing the StackOverflow : each constructor makes a call to the other one



来源:https://stackoverflow.com/questions/55497618/java-lang-stackoverflowerror-between-two-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!