StackOverFlow
当我尝试运行我的井字游戏程序时,我正在努力解决这个异常。
通过阅读堆栈跟踪,我知道StackOverFlow
错误是循环关系的结果。这是因为当我miniFrame
在构造函数内部实例化类时TicTacToeFrame
,一个TicTacToeFrame
对象被用作miniFrame
构造函数的参数。结果,这会导致无限递归。
Exception in thread "main" Exception in thread "main" Exception in thread "main" java.lang.StackOverflowError
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Dialog.<init>(Unknown Source)
at java.awt.Dialog.<init>(Unknown Source)
at javax.swing.JDialog.<init>(Unknown Source)
at javax.swing.JDialog.<init>(Unknown Source)
at javax.swing.JDialog.<init>(Unknown Source)
at miniFrame.<init>(miniFrame.java:12)
at TicTacToeFrame.<init>(TicTacToeFrame.java:26)
at miniFrame.<init>(miniFrame.java:9)
at TicTacToeFrame.<init>(TicTacToeFrame.java:26)
at miniFrame.<init>(miniFrame.java:9)
at TicTacToeFrame.<init>(TicTacToeFrame.java:26)
at miniFrame.<init>(miniFrame.java:9)
at TicTacToeFrame.<init>(TicTacToeFrame.java:26)
at miniFrame.<init>(miniFrame.java:9)
at TicTacToeFrame.<init>(TicTacToeFrame.java:26)
at miniFrame.<init>(miniFrame.java:9)
at TicTacToeFrame.<init>(TicTacToeFrame.java:26)
TicTacToeFrame
构造函数实例化miniFrame dialogBox = new miniFrame (this)
.
//IMPORT JAVA LIBARARY
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
public class TicTacToeFrame extends JFrame {
public char whoseTurn = 'X';
public Cell [] [] cells = new Cell [3] [3];
JLabel jlblStatus = new JLabel ("X's turn to play");
public boolean gameOver = false;
public JPanel panel;
JTextField textField;
public TicTacToeFrame () {
miniFrame dialogBox = new miniFrame (this);//This is line 26 referred to in the stack trace
dialogBox.returnName ();
panel = new JPanel (new GridLayout (3, 3, 0, 0));
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
panel.add (cells [i] [j] = new Cell(this));
}
}
panel.setBorder (new LineBorder (Color.red, 1));
jlblStatus.setBorder (new LineBorder (Color.yellow, 1));
add (panel, BorderLayout.CENTER);
add (jlblStatus, BorderLayout.SOUTH);
}
这是将miniFrame
对象TicTacToeFrame
作为参数的构造函数。但是我不明白为什么JVM会StackOverFlow
在第9行发现错误:
import javax.swing.*;
import java.awt.event.*;
public class miniFrame extends JDialog implements ActionListener {
JTextField textField;
JButton Submit;
JLabel playerX;
TicTacToeFrame Label = new TicTacToeFrame ();//This is line 9 referred to in the stack trace. Why does the JVM find an error on this line?
public miniFrame (TicTacToeFrame parent) {
super (parent);//This is line 12 referred in the stack trace
textField = new JTextField ("ENTER YOUR NAME", 20);
Submit = new JButton ("Submit");
playerX = new JLabel ();
Submit.addActionListener (this);
add (playerX);
add (textField);
add (Submit);
}
我可以使用的另一种解决方案是-Xss
使用命令行增加堆栈帧大小的标志。但我觉得这可能是一种逃避。