Java Swing无法删除组件

Java Swing无法删除组件,java,swing,inner-classes,Java,Swing,Inner Classes,我正在尝试构建一个问答游戏,在用户点击带有答案的按钮后重新播放 我在4个按钮中添加了一个动作侦听器。当点击按钮时,假设它到达扩展JFrame的外部类,并删除扩展JPanel的QuestionPanel。然后创建一个新的问题面板并将其添加回框架 中的层次结构如下所示: 大型机(JFrame)->问题面板(JPanel)->选项面板(JPanel)->按钮(JButton) 主机(外部类) ->问题小组(内部班级) ->选项面板(内部类别) 但它只是在执行过程中冻结 正如许多人指出的,您最好更改组

我正在尝试构建一个问答游戏,在用户点击带有答案的按钮后重新播放

我在4个按钮中添加了一个动作侦听器。当点击按钮时,假设它到达扩展JFrame的外部类,并删除扩展JPanel的QuestionPanel。然后创建一个新的问题面板并将其添加回框架

中的层次结构如下所示:
大型机(JFrame)->问题面板(JPanel)->选项面板(JPanel)->按钮(JButton)

主机(外部类) ->问题小组(内部班级) ->选项面板(内部类别)

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


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

我假设您的问题面板包含一个显示问题的
JLabel
JTextComponent
。为什么不改变问题的内容呢?查找方法
setText()
。假设到达扩展JFrame的外部类并删除扩展JPanel的QuestionPanel,也许最好一次性创建QuestionPanel并更新JLabel和JButtons的文本。或者使用CardLayout,以便可以快速更改可见视图。使用如中所示的。
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);
     }
});