Home > OS >  I have a Exception (StackOverflowError)
I have a Exception (StackOverflowError)

Time:05-23

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 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) {

   }
}``` 

CodePudding user response:

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.

CodePudding user response:

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);
       ...
}
  • Related