【发布时间】:2021-02-06 09:25:24
【问题描述】:
我正在尝试构建一个问答游戏,在用户单击带有答案的按钮后重新呈现自身。
我为 4 个按钮添加了一个动作监听器。单击按钮时,假设到达扩展 JFrame 的外部类并删除扩展 JPanel 的 QuestionPanel。然后创建一个新的 QuestionPanel 并将其添加回框架。
层次结构是这样的:
MainFrame (JFrame) -> QuestionPanel (JPanel) -> optionPanel (JPanel) -> 按钮 (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);
}
});
【问题讨论】:
-
我假设您的 问题面板 包含显示问题的
JLabel或JTextComponent。为什么不直接更改问题的文本?寻找方法setText()。 -
假设到达扩展 JFrame 的外部类并删除扩展 JPanel 的 QuestionPanel 也许最好创建一次 QuestionPanel 并更新文本JLabel 和 JButtons。
-
或使用 CardLayout 以便您可以快速更改可见视图。
-
使用
CardLayout,如this answer所示。
标签: java swing inner-classes