Skip to content

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

      boolean result = false;
      JButton target = (JButton) e.getSource();
      result = MainFrame.this.questions[currentQuestion].checkAnswer(target.getText());
      if(currentQuestion != (questions.length - 1)){
            //qPanel is the instance of QuestionPanel
            qPanel = new QuestionPanel(questions[currentQuestion]);


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.