title: How to add elements to GridBagLayout from paintComponent()
body: <p>In the following code, in the constructor the label gets correctly created and displayed on the screen. Note that it is added to the <code>GridBagLayout()</code> layout manager. Then, in the <code>paintComponent()</code> method that we override from the JPanel extention, we reset the contents of the JPanel and add the label again. However, this time the label is not displayed on the screen. I would expect it to be added normally, but it is not. Why is this the case?</p>
  <pre><code>public class MyPanel extends JPanel {
  
      private final GridBagConstraints grid = new GridBagConstraints();
  
      public MyPanel () {
          setBounds(200, 200, 1000, 1000);
          setLayout(new GridBagLayout());
          setOpaque(false);
          setVisible(false);
  
          grid.anchor = GridBagConstraints.PAGE_END;
  
          JLabel oldLabel = new JLabel(&quot;This is an old Label&quot;);
          add(oldLabel, grid);
      }
  
      @Override
      public void paintComponent(Graphics g) {
          super.paintComponent(g);
  
          removeAll();
  
          JLabel newLabel = new JLabel(&quot;This is a new Label&quot;);
          add(newLabel, grid);
  
          revalidate();
          repaint();
      }
  
  }
  </code></pre>
  <p>In this example the component is known, but in my situation I have a variable amount of components that is not known beforehand and changes during the program.</p>