【问题标题】:Java Swing unable to remove a componentJava Swing 无法删除组件
【发布时间】: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);
     }
});

【问题讨论】:

  • 我假设您的 问题面板 包含显示问题的 JLabelJTextComponent。为什么不直接更改问题的文本?寻找方法setText()
  • 假设到达扩展 JFrame 的外部类并删除扩展 JPanel 的 QuestionPanel 也许最好创建一次 QuestionPanel 并更新文本JLabel 和 JButtons。
  • 或使用 CardLayout 以便您可以快速更改可见视图。
  • 使用CardLayout,如this answer所示。

标签: java swing inner-classes


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-04-19
    • 2017-07-11
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多