how to return to my main panel in java?

1.4k views Asked by At

I want to back to the main panel in my java application with a jMenuItem, my panels and other stuff are set with a CardLayout. So I have 3 panels and from any of them I want to be able to return to the first panel using this menu item to start a new analysis. I have tried with the property setVisible with no results. Any suggestion? thanks in advance.

enter image description here

1

There are 1 answers

0
Jeet On

The below example may help you.

import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class cardLayout {
    JFrame objFrm = new JFrame("CardLayout Demo");
    JPanel pnl1, pnl2, pnl3, pnlMain;
    JMenuBar mBar;
    JMenu mnu;
    JMenuItem mnuItem;
    public void show() {
        pnl1 = new JPanel(new CardLayout());
        pnl1.add(new JLabel("Panle 1"));
        pnl2 = new JPanel(new CardLayout());
        pnl2.add(new JLabel("Panle 2"));
        pnl3 = new JPanel(new CardLayout());
        pnl3.add(new JLabel("Panle 3"));

        pnlMain = new JPanel();
        pnlMain.setLayout(new CardLayout());

        pnlMain.add(pnl1);
        pnlMain.add(pnl2);
        pnlMain.add(pnl3);

        objFrm.setLayout(new CardLayout());
        objFrm.add(pnlMain);

        objFrm.setSize(300, 300);
        mBar = new JMenuBar();
        mnu = new JMenu("Menu");
        mnuItem = new JMenuItem("Change Panel");
        mnuItem.addActionListener((java.awt.event.ActionEvent evt) -> {
            ((CardLayout) pnlMain.getLayout()).next(pnlMain);
        });
        mBar.add(mnu);
        mnu.add(mnuItem);
        objFrm.setJMenuBar(mBar);
        objFrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        objFrm.setVisible(true);
    }
    public static void main(String[] args) {
        new cardLayout().show();
    }
}

At first i added the three Jpanels(pnl1,pnl2,pnl3) to JFrame having card layout and it didn't worked and throw error. So instead i created one more panel (pnlMain) with cardlayout and added all the three panels. And now it worked fine on menu item click event.