Here's what I want to do. When I select any menu item it should add a panel to the frame.
eg. If I click on New, it should add pan1 to the frame. Any other menu item selected should replace the current panel with another one.
Below is a sample code that I was trying to modify to achieve what I wanted but with no success. I would really appreciate it if someone could point me in the right direction.
Code:
import java.awt.*;
import java.awt.event.*;;
import javax.swing.*;
class MenuActionListener implements ActionListener {
Menu m = new Menu();
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "New")
{
System.out.println("You selected new");
m.panel1();
}
if(e.getActionCommand() == "Edit")
{
System.out.println("You selected Edit");
}
}
}
public class Menu {
JFrame frame = new JFrame("MenuSample Example");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pan1, pan2;
JButton b0, b1;
public Menu() {
b0 = new JButton("First button");
b1 = new JButton("Default Button");
pan1 = new JPanel();
pan2 = new JPanel();
}
public void panel1() {
pan1.add(b0);
frame.add(pan1);
frame.setVisible(true);
// frame.add(pan1, BorderLayout.CENTER);
}
public void MainMenu() {
// JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
pan2.add(b1);
frame.add(pan2);
// File Menu, F - Mnemonic
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
JMenuItem newMenuItem = new JMenuItem("New");
newMenuItem.addActionListener(new MenuActionListener());
fileMenu.add(newMenuItem);
JMenuItem MenuItem = new JMenuItem("Edit");
MenuItem.addActionListener(new MenuActionListener());
fileMenu.add(MenuItem);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(false);
}
public static void main(String args[]) {
Menu mM = new Menu();
mM.MainMenu();
}
}