How do I return to the main panel in java?
I want to go back to the main panel in my java application using jMenuItem, my panels and other items are set using CardLayout. So I have 3 panels and from any of them I want to go back to the first panel using this menu item to start a new analysis. I tried using the setVisible property with no results. Any suggestion? thanks in advance.
+3
source to share
1 answer
The example below might 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();
}
}
I first added three Jpanels (pnl1, pnl2, pnl3) to a JFrame having a map layout and it didn't work and was throwing an error. So instead I created another panel (pnlMain) with cardlayout and added all three panels. And now it has done a great job with the click event of the menu item.
0
source to share