import javax.swing.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public class WrongQuestionSet extends JFrame{
private JLabel[] questionLabels;
private JLabel[][] rightButton;
private JLabel[][] optionLabels;
private ArrayList<Question> wrongQuestions = new ArrayList<>();
public WrongQuestionSet(JPanel rightPanel){
try {
FileInputStream fileIn = new FileInputStream("wrong_questions.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
wrongQuestions = (ArrayList<Question>)in.readObject();
optionLabels = new JLabel[wrongQuestions.size()][4];
questionLabels = new JLabel[wrongQuestions.size()];
rightButton = new JLabel[wrongQuestions.size()][4];
JPanel panel = new JPanel(new GridLayout(wrongQuestions.size() * 5, 1));
for (int i = 0; i < wrongQuestions.size(); i++) {
// 题目
questionLabels[i] = new JLabel((i+1) + ". " + wrongQuestions.get(i).getContent());
System.out.println(questionLabels[i]); //1
panel.add(questionLabels[i]);
//选项
for (int j = 0; j < wrongQuestions.get(i).getOptions().length; j++) {
optionLabels[i][j] = new JLabel((char) ('A' + j) + ". " + wrongQuestions.get(i).getOptions()[j]);
System.out.println(optionLabels[i][j]);
panel.add(optionLabels[i][j]);
}
// 正确答案
String rightAnswer = "";
for (int j = 0; j < wrongQuestions.get(i).getOptions().length; j++) {
if (wrongQuestions.get(i).getScores()[j] == 1) {
rightAnswer += (char)('A' + j);
}
}
rightButton[i][0] = new JLabel("正确答案:" + rightAnswer);
panel.add(rightButton[i][0]);
// Analysis
JLabel analysisLabel = new JLabel("Analysis: " + wrongQuestions.get(i).getAnalysis());
panel.add(analysisLabel);
}
JScrollPane scrollPane = new JScrollPane(panel);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(scrollPane, BorderLayout.CENTER);
rightPanel.removeAll();
rightPanel.add(mainPanel,BorderLayout.CENTER);
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("Question class not found");
c.printStackTrace();
}
}
}
为什么逻辑没有出错,但是运行结果一塌糊涂啊
1.序号对不上
2.正确的输出顺序应该是题干、选项abcd、正确答案、analysis分析(我代码逻辑没错啊)
GridLayout布局中将行数和列数都设置为非零值时,指定的列数将被忽略。所以你这里将列数指定为 0 就可以正常显示了。
JPanel panel = new JPanel(new GridLayout(0, 1));
PS: 对Swing还是不熟,参考了以前的问答才找到答案。 https://ask.csdn.net/questions/687788