Java Swing 无法删除组件

Java Swing unable to remove a component

我正在尝试构建一个问答游戏,它会在用户点击带有答案的按钮后自行重新呈现。

我已经为 4 个按钮添加了一个动作侦听器。单击按钮时,假设到达扩展 JFrame 的外部 class 并删除扩展 JPanel 的 QuestionPanel。然后创建一个新的 QuestionPanel 并将其添加回框架。

中的层次结构如下:
MainFrame (JFrame) -> QuestionPanel (JPanel) -> optionPanel (JPanel) -> 按钮 (JButton)

MainFrame(外部class) -> 问题面板(内部 class) -> 选项面板(内部 class)

但它只是在执行过程中冻结

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);
     }
});

正如许多人指出的那样,您最好更改标签等组件内的文本,而不是删除 Jpanel 并替换它。根本不需要这样做,尤其是只是向用户显示文本。