-3

I have this kind of error:

Exception in thread "main" Exception in thread "main" Exception in thread "main" java.lang.StackOverflowError

My Code (actually by BroCode):

public class SnakeGame {

    public static void main(String[] args) {
        GameFrame frame = new GameFrame();

    }
}
import javax.swing.JFrame;

public class GameFrame extends JFrame {

    public GameFrame() {
        this.add(new GameFrame());
        this.setTitle("Snake");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.pack();
        this.setVisible(true);
        this.setLocationRelativeTo(null);
    }
}
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GamePanel extends JPanel implements ActionListener {

    public GamePanel() {

    }
    @Override
    public void actionPerformed(ActionEvent e) {

    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Anonym
  • 1
  • 1
  • 6
    Why does `GameFrame` add a new `GameFrame` to itself?` – tkausl May 22 '22 at 20:26
  • 1
    This seems to be update to [Java Snake Game Restart Button Bug](https://stackoverflow.com/q/72340663) (now deleted and posted from different account). If you want to clarify problem with your implementation, instead of posting new question simply edit previous one. – Pshemo May 22 '22 at 20:31

2 Answers2

0

As @tkausl mentioned - you are calling new GameFrame() as infinity loop inside the constructor. These causes the StackOverflowException. If you want to have a JFrame in the GameFrame you should simple call the constructor of these class directly.

Jelmen
  • 173
  • 9
0

In Java, the new keyword calls the constructor of the class. So when you do

public GameFrame() {
       this.add(new GameFrame());
       ...
}

you're recursively calling the GameFrame constructor "infinitely" many times (or as many times as needed to cause a StackOverflowError to be exact). If you want to access the current instance of a class, use the this keyword (https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html). So your new code would become

public GameFrame() {
       this.add(this);
       ...
}
Badr B
  • 998
  • 1
  • 9
  • 17