title: Change JPanel Background Color in JFrame
body: <p>I'm trying to change the background of a JPanel inside of a JFrame. JFrame consist of JPanels much like a grid. I"m trying to change a random JPanel inside of the JFrame and see the color change on each pass through the loop. Here is what I've got so far.</p>
  
  <pre><code>private static JPanel panel;
  private static int index;
  
  public static void main(String[] args)
  {
      JFrame window = new JFrame();
      window. setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
      window.setSize(600, 600);
      GridLayout layout = new GridLayout(50, 50, 3, 3);
      panel = new JPanel(layout);
      panel.setSize(600, 600);
  
      //Initialize the JFrame with JPanels that
      //are all white.
      InitializeGrid(panel);
  
      window.add(panel);
      window.validate();
      window.setVisible(true);
  
  
      MainLoop();
  }
  
  private static void MainLoop()
  {
  
        Component[] componentArrayTwo = panel.getComponents();
  
        int index = 0;
  
        while(true)
        {
          JPanel currentPanel = (JPanel) componentArrayTwo[index];
              currentPanel.setBackground(Color.GREEN);
              index++;
  
            if(index == 1600)
            {
                //Restart again
                index = 0;
            }
  
            //Colors everything back to white.
            Reset();
        }    
  }
  
  private static void InitializeGrid(JPanel panel)
  {
        //40 x 40 = 1600
      for(int i = 0; i &lt; 1600; i++)
      {
          JPanel cellPanel = new JPanel();
  
          cellPanel.setMinimumSize(new Dimension(3, 3));
          cellPanel.setMaximumSize(new Dimension(3, 3));
          cellPanel.setPreferredSize(new Dimension(3, 3));
          cellPanel.setBackground(Color.WHITE);
  
          panel.add(cellPanel);
      }
  }
  
  /*************************************************************************/
  //NAME: Reset
  //DESCRIPTION: Resets all the cells back to white which is executed on
  //each iteration through the loop.
  /*************************************************************************/
  private static void Reset()
  {
      Component[] componentArrayTwo = panel.getComponents();
  
      for(Component individualComponent : componentArrayTwo ) 
      {
          JPanel panelToColor = (JPanel) individualComponent;
  
  
          panelToColor.setBackground(Color.WHITE);
  
      }
  }
  </code></pre>
  
  <p>If I uncomment line the panel.add(individualPanel) this will show the color change, but it keeps adding more and more JPanels to the JFrame. However, commenting this line lets me change the color but doesn't show any changes in the JFrame. I've tried changing various pieces in this code but so far I've been unsuccessful. What should happen is that on each pass through the loop I should see a Green JPanel show up in random spots in the JFrame. If anyone could help I'd appreciate it.</p>