Search code examples
javaswingjframejpanelstack-overflow

Creating an object from a JPanel class giving overflow error


I am trying to create an object from a class that extends JPanel but when i run it I get an StackOverflowError. Error message: "Exception in thread "main" java.lang.StackOverflowError"

Main.java

public class Main {

public static int width = 600, height = 400;
public static String title = "tec9meister";

public static void createWindow(){
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(width, height);
    frame.setResizable(false);

    //createPane(frame);

    PaintPanel p = new PaintPanel();
    p.setSize(100,100);
    frame.add(p);

    frame.setVisible(true);
}

private static void createPane(JFrame frame) {
    PaintPanel pane = new PaintPanel();

    pane.setSize(width, height);
    pane.setFocusable(true);
    pane.requestFocus();

    frame.add(pane);
}

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

PaintPanel.java

public class PaintPanel extends JPanel{

public PaintPanel() {

    Target t = new Target(100, 100, 10, 10);

}
}

Target.java

public class Target extends PaintPanel {

private int x;
private int y;
private int width;
private int height;

public Target(int x, int y, int width, int height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;

}

Solution

  • If you try to create an instance of a class that extends PaintPanel within the constructor of PaintPanel, this will cause a StackOverflowError due to recursive calls of the same constructor. In particular, TestClass could not be Target since Target extends PaintPanel.