Skip to content
Advertisement

Java Swing unable to remove a component

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
enter image description here

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement