Search code examples
swingjframejpanel

How to load next panel in a frame, which is already set with a panel using setContentPanel()


I've a JFrame class and two JPanel classes. At first, I want to add Panel1 when Jframe main() is invoked, and when "Next>" button in the Panel1 is clicked, want to open Panel2.

Now what I'm trying is run JFrame, which is opening Panel1 by calling jFrameObj.setContentPane(Panel1). Later my cotrol moves to Panel1 and Now how can I do setContentPane(Panel2) on the same jFrameObj ?

Is this the correct approach for my functionality? Recommend me if any other approach is there?


Solution

  • This is a simple program illustrating the usage of a CardLayout for the required task. You might also want to have a look into this article (from 2005 so some things may have changed).

    import java.awt.*;
    import javax.swing.*;
    
    public class CardLayoutTestApplet extends JApplet {
    
        @Override
        public void init() {
            final Container pane = getContentPane();
            final CardLayout paneLayout = new CardLayout();
    
            JPanel panel1 = new JPanel();
            JButton button1 = new JButton("Next>>");
            panel1.add(button1);
    
            button1.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    paneLayout.show(pane, "Card2");
                }
            });
    
            JPanel panel2 = new JPanel();
            panel2.add(new JLabel("Second Panel"));
    
            pane.setLayout(paneLayout);
            pane.add(panel1, "Card1");
            pane.add(panel2, "Card2");
        }
    }