How do I replace a JPanel with another JPanel in the same position?


I have a JFrame with about four frames. After a given action I want to replace one panel with another in the same position. My method for switching them looks like this (the this object is a class which extends JFrame):

 public void switchPanel(){

The original creation of the window looks like this:


You ask:

How can I replace one JPanel with another JPanel in the same position?

Very easily: use a CardLayout as this tool was built for just this situation.

If you had the following constants:

public static final String INTRO_PANEL = "intro panel";
public static final String QUESTION_PANEL = "question panel";

and added your JPanel's like so

mainPanel.add(introPanel, INTRO_PANEL);
mainPanel.add(questionPanel, QUESTION_PANEL);, INTRO_PANEL);

Then you could swap JPanels with:, QUESTION_PANEL);

would be all that were needed to show the swap, assuming that QUESTION_PANEL is a String constant that was used when you added the questionPanel to the mainPanel, and that the mainPanel uses the CardLayout.

For example:

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

public class SwapPanels extends JPanel {
   public static final String INTRO_PANEL = "intro panel";
   public static final String QUESTION_PANEL = "question panel";
   private static final int PREF_W = 500;
   private static final int PREF_H = 400;
   private CardLayout cardLayout = new CardLayout();
   private JPanel introPanel;
   private JPanel questionPanel;
   private Random random = new Random();

   public SwapPanels() {
      introPanel = createPanel("Introduction");
      questionPanel = createPanel("Question");
      add(introPanel, INTRO_PANEL);
      add(questionPanel, QUESTION_PANEL);

      int delay = 3 * 1000; // show intro for 3 seconds
      new Timer(delay, new ActionListener() {

         public void actionPerformed(ActionEvent e) {
            ((Timer) e.getSource()).stop();

   private JPanel createPanel(String title) {
      int rgb = random.nextInt();
      Color color = new Color(rgb);
      JPanel panel = new JPanel(new GridBagLayout());
      panel.setBorder(BorderFactory.createLineBorder(color, 60));
      panel.add(new JLabel(title));
      return panel;

   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      return new Dimension(PREF_W, PREF_H);

   private static void createAndShowGui() {
      SwapPanels mainPanel = new SwapPanels();

      JFrame frame = new JFrame("SwapPanels");

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {