我正在尝试构建一个测验游戏,在用户单击带有答案的按钮后重新呈现自己。
我为 4 个按钮添加了一个动作侦听器。单击按钮时,假设到达扩展 JFrame 的外部类并删除扩展 JPanel 的 QuestionPanel。然后创建一个新的 QuestionPanel 并将其添加回框架。
层次结构如下:
MainFrame (JFrame) -> QuestionPanel (JPanel) -> optionPanel (JPanel) -> button (JButton)
MainFrame(外部类)-> QuestionPanel(内部类)-> OptionPanel(内部类)
button.addActionListener(e->{
boolean result = false;
JButton target = (JButton) e.getSource();
result = MainFrame.this.questions[currentQuestion].checkAnswer(target.getText());
System.out.println(questions.length);
if(currentQuestion != (questions.length - 1)){
MainFrame.this.remove(qPanel);
//qPanel is the instance of QuestionPanel
currentQuestion++;
qPanel = new QuestionPanel(questions[currentQuestion]);
MainFrame.this.add(qPanel);
}
});
就像许多人指出的那样,最好更改组件内的文本(如 Label),而不是删除 Jpanel 并替换它。根本没有必要这样做,尤其是只需要向用户显示文本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句