Java Swing无法移除组件。

huangapple go评论66阅读模式
英文:

Java Swing unable to remove a component

问题

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

我已经为4个按钮添加了动作监听器。当按钮被点击时,它应该达到扩展了JFrame的外部类,然后删除扩展了JPanel的QuestionPanel。然后创建一个新的QuestionPanel,并将其添加回框架。

层次结构如下:
MainFrame(JFrame)-> QuestionPanel(JPanel)-> optionPanel(JPanel)-> button(JButton)

MainFrame(外部类)
-> QuestionPanel(内部类)
-> OptionPanel(内部类)

但在执行过程中它会冻结
Java Swing无法移除组件。

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是QuestionPanel的实例
            currentQuestion++;
            qPanel = new QuestionPanel(questions[currentQuestion]);
            MainFrame.this.add(qPanel);
     }
});
英文:

I am trying to build a quiz game that rerender itself after user click on the button with answer.

I have added an action listener to 4 buttons. When the button is clicked, it is suppose to reach the outer class which extend JFrame and remove the QuestionPanel that extends the JPanel. And then create a new QuestionPanel and add it back to the frame.

The hierarchy in goes like this :
MainFrame (JFrame) -> QuestionPanel (JPanel) -> optionPanel (JPanel) -> button (JButton)

MainFrame(outer class)
-> QuestionPanel (inner class)
-> OptionPanel (inner class)

But it just freeze during execution
Java Swing无法移除组件。

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

答案1

得分: 0

许多人指出,你最好修改组件内部的文本,比如一个标签(Label),而不是移除一个 JPanel 并替换它。其实没有必要这样做,尤其是只是为了向用户显示文本。

英文:

Like many pointed out, you would be better off changing the text inside a component like a Label rather than removing a Jpanel and replacing it. There is simply no need for that, especially just to display text to a user.

huangapple
  • 本文由 发表于 2020年10月23日 17:59:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64497866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定