问题
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