Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8291921
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T13:17:48+00:00 2026-06-08T13:17:48+00:00

I have 2 JPanels and 1 JFrame, and I’m trying to switch between panels

  • 0

I have 2 JPanels and 1 JFrame, and I’m trying to switch between panels when I click a button..
I don’t want to use CardLayout, because I want different panels and with CardLayouts I just can have the same button for both.
My code is:

package javaapplication2;

import javax.swing.JPanel;

public class NewJFrame extends javax.swing.JFrame {
/**
 * Creates new form NewJFrame
 */JPanel panel1 = new JPanel();
 JPanel panel2 = new JPanel();
public NewJFrame() {
    initComponents();
}

private void initComponents() {

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setBackground(new java.awt.Color(121, 183, 60));
    setSize(200, 300);
    setResizable(false);



    /**panel1**/
     jButton1 = new javax.swing.JButton();

    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton1MouseClicked(evt);
        }
    });
    jButton1.setText("jButton1");
     panel1.setBackground(new java.awt.Color(121, 183, 60));
    panel1.setMaximumSize(new java.awt.Dimension(100, 200));
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(panel1);
    panel1.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(164, 164, 164)
            .addComponent(jButton1)
            .addContainerGap(172, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(115, 115, 115)
            .addComponent(jButton1)
            .addContainerGap(158, Short.MAX_VALUE))
    );

    /**panel2**/

       jButton2 = new javax.swing.JButton();

    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton2MouseClicked(evt);
        }
    });
    jButton2.setText("jButton2");
     panel2.setBackground(new java.awt.Color(101, 13, 61));
    panel2.setMaximumSize(new java.awt.Dimension(100, 200));
    javax.swing.GroupLayout layout2 = new javax.swing.GroupLayout(panel2);
    panel2.setLayout(layout2);
    layout2.setHorizontalGroup(
        layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout2.createSequentialGroup()
            .addGap(164, 164, 164)
            .addComponent(jButton2)
            .addContainerGap(172, Short.MAX_VALUE))
    );
    layout2.setVerticalGroup(
        layout2.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout2.createSequentialGroup()
            .addGap(115, 115, 115)
            .addComponent(jButton2)
            .addContainerGap(158, Short.MAX_VALUE))
    );
   add(panel2);
    pack();
}


public void changePanel(){
    getContentPane().removeAll();
    add(panel1);
    invalidate();
    repaint();
}

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
    changePanel();
}
 private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
    changePanel();
}

private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T13:17:50+00:00Added an answer on June 8, 2026 at 1:17 pm

    Here is one small example for your help :

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class CardLayoutExample
    {
        private JPanel contentPane;
        private MyPanel panel1;
        private MyPanel2 panel2;
    
        private void displayGUI()
        {
            JFrame frame = new JFrame("Card Layout Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel contentPane = new JPanel();
            contentPane.setBorder(
                BorderFactory.createEmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new CardLayout());
            panel1 = new MyPanel(contentPane);
            panel2 = new MyPanel2(contentPane);
            contentPane.add(panel1, "Panel 1"); 
            contentPane.add(panel2, "Panel 2");
            frame.setContentPane(contentPane);
            frame.pack();   
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String... args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new CardLayoutExample().displayGUI();
                }
            });
        }
    }
    
    class MyPanel extends JPanel 
    {
        private JButton jcomp4;
        private JPanel contentPane;
    
        public MyPanel(JPanel panel) 
        {
            contentPane = panel;
            setOpaque(true);
            setBackground(Color.RED.darker().darker());
            //construct components
            jcomp4 = new JButton ("openNewWindow");
            jcomp4.addActionListener( new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    CardLayout cardLayout = (CardLayout) contentPane.getLayout();
                    cardLayout.next(contentPane);
                }
            });
            add(jcomp4);
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return (new Dimension(500, 500));
        }
    }
    
    class MyPanel2 extends JPanel 
    {
    
        private JButton jcomp1;
        private JPanel contentPane;
    
        public MyPanel2(JPanel panel) 
        {   
            contentPane = panel;
    
            setOpaque(true);
            setBackground(Color.GREEN.darker().darker());
    
            //construct components
            jcomp1 = new JButton ("Back");
            jcomp1.addActionListener( new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    CardLayout cardLayout = (CardLayout) contentPane.getLayout();
                    cardLayout.next(contentPane);
                }
            });
    
            add(jcomp1);
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return (new Dimension(500, 500));
        }
    }
    

    LATEST EDIT

    Show JPanel of your choice, inside CardLayout

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class CardLayoutExample
    {
        private JPanel contentPane;
        private MyPanel panel1;
        private MyPanel2 panel2;
        private MyPanel2 panel3;
        private JComboBox choiceBox;
        private String[] choices = {
                                    "Panel 1",
                                    "Panel 2",
                                    "Panel 3"
                                   };
    
        private void displayGUI()
        {
            JFrame frame = new JFrame("Card Layout Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel contentPane = new JPanel();
            contentPane.setBorder(
                BorderFactory.createEmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new CardLayout());
    
            choiceBox = new JComboBox(choices);        
    
            panel1 = new MyPanel(contentPane, this);
            panel2 = new MyPanel2(contentPane
                    , Color.GREEN.darker().darker(), this);
            panel3 = new MyPanel2(contentPane
                    , Color.DARK_GRAY, this);   
    
            contentPane.add(panel1, "Panel 1"); 
            contentPane.add(panel2, "Panel 2");
            contentPane.add(panel3, "Panel 3");         
    
            frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
            frame.getContentPane().add(contentPane, BorderLayout.CENTER);       
            frame.pack();   
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public JComboBox getChoiceBox()
        {
            return choiceBox;
        }
    
        public static void main(String... args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new CardLayoutExample().displayGUI();
                }
            });
        }
    }
    
    class MyPanel extends JPanel 
    {
        private JButton jcomp4;
        private JPanel contentPane;
        private JComboBox choiceBox;
    
        public MyPanel(JPanel panel, CardLayoutExample cle) 
        {
            choiceBox = cle.getChoiceBox();
            contentPane = panel;
            setOpaque(true);
            setBackground(Color.RED.darker().darker());
            //construct components
            jcomp4 = new JButton ("Show New Panel");
            jcomp4.addActionListener( new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    String changeToPanel = (String) choiceBox.getSelectedItem();
                    CardLayout cardLayout = (CardLayout) contentPane.getLayout();
                    cardLayout.show(contentPane, changeToPanel);
                }
            });
            add(jcomp4);
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return (new Dimension(500, 500));
        }
    }
    
    class MyPanel2 extends JPanel 
    {
    
        private JButton jcomp1;
        private JPanel contentPane;
        private Color backgroundColour;
        private JComboBox choiceBox;
    
        public MyPanel2(JPanel panel, Color c, CardLayoutExample cle) 
        {   
            contentPane = panel;
            backgroundColour = c;
            choiceBox = cle.getChoiceBox();
    
            setOpaque(true);
            setBackground(backgroundColour);
    
            //construct components
            jcomp1 = new JButton ("Show New Panel");
            jcomp1.addActionListener( new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    String changeToPanel = (String) choiceBox.getSelectedItem();
                    CardLayout cardLayout = (CardLayout) contentPane.getLayout();
                    cardLayout.show(contentPane, changeToPanel);
                }
            });
    
            add(jcomp1);
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return (new Dimension(500, 500));
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have 50 JPanels in one JFrame and I want all of them to
I have a JFrame containing a set of JPanels in a CardLayout . Each
I have a JFrame with four components: three JPanels and a JTabbedPane. Two panels
I have created jframe in which jpanels are added dynamically what i can't do
I have sever JPanels which have to be ordered vertically. For that I want
I have a frame with 4 JPanels and 1 JScrollPane, the 4 panels are
I have 3 JPanels on my JFrame. Anyhow the JPanels expand vertically and horizontally
I have a JFrame which has 3 JPanels in GridBagLayout .. Now, when I
I have a JFrame with two JPanels inside. One is set on west, other
I want to add two jPanels to a JFrame side by side. the two

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.