我正在编写一个程序,该程序可以将一组问题写入文件以供另一个程序读取。可能的答案输入到底部的 JTextFields 中。它有代码确保最后不会有超过一个空白 JTextField。当我输入答案时,它会在不同的点抛出 StackOverflowError。
堆栈跟踪:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232)
at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232)
at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232)
at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232)
和代码:现在缩短了!!!
package writer;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class MyPanel extends JPanel implements KeyListener
{
private MutableQuestion current;
private WriterPanel writer;
private JPanel top=new JPanel(new BorderLayout()),answerPanel=new JPanel(new GridLayout(0,1));
private JSplitPane split;
private JTextField title=new JTextField();
private JTextArea question=new JTextArea();
private ArrayList<JTextField> answers=new ArrayList<JTextField>();
public MyPanel()
{
super(new BorderLayout());
this.add(title,BorderLayout.PAGE_START);
split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,new JScrollPane(question),new JScrollPane(answerPanel));
split.setDividerLocation(150);
this.add(split,BorderLayout.CENTER);
answers.add(new JTextField());
answerPanel.add(answers.get(0));
answers.get(0).addKeyListener(this);
}
private void back(){}
private void fitTitle(){}
private void fixAnswers()
{
//System.out.println(answers);
while(answers.get(answers.size()-1).getText().equals("")&&answers.size()>1&&answers.get(answers.size()-2).getText().equals(""))
removeAnswer(answers.size()-1);
if(!answers.get(answers.size()-1).getText().equals(""))
{
answers.add(new JTextField());
answerPanel.add(answers.get(answers.size()-1));
answers.get(answers.size()-2).removeKeyListener(this);
//answers.get(answers.size()-1);
answerPanel.revalidate();
}
answers.get(answers.size()-1).addKeyListener(this);
}
private void removeAnswer(int i){}
public void keyTyped(KeyEvent e)
{
fixAnswers();
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void newQuestion(){}
public void loadQuestion(int i){}
public void saveQuestion(){}
public void loadQuestion(MutableQuestion q){}
public static void main(String[] args)
{
JFrame j=new JFrame();
j.setSize(600,600);
j.add(new MyPanel());
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
}
}