java - Java Swing 无法删除组件
问题描述
我正在尝试构建一个问答游戏,在用户单击带有答案的按钮后重新呈现自身。
我为 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 并替换它。根本没有必要这样做,尤其是仅仅向用户显示文本。
推荐阅读
- nestjs - 单元测试 NestJS 控制器的正确方法?
- java - 状态从启动到崩溃的弹簧靴?
- c - Prim 的最小生成树中的重复边
- python - AWS lambda(python):安装 psycopg2 的 Dockerfile?
- excel - 在excel VBA中复制和重命名工作表
- javascript - 在清理画布绘图时删除其他绘图
- java - gradle多个存储库不起作用
- arrays - 在 c 中打印数组时遇到问题
- javascript - 反应输入值不适用于状态
- amazon-web-services - 从控制台运行 AWS Lambda 函数会产生 TypeError