Java JMenu add to JFrame
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; //from ww w. j av a 2 s. c o m public class Main implements ActionListener { public Main () { // Create a new JFrame container. JFrame jfrm = new JFrame("Menu Demo"); // Specify FlowLayout for the layout manager. jfrm.setLayout(new FlowLayout()); // Give the frame an initial size. jfrm.setSize(220, 200); // Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create the menu bar. JMenuBar jmb = new JMenuBar(); // Create the File menu. JMenu jmFile = new JMenu("File"); JMenuItem jmiOpen = new JMenuItem("Open"); JMenuItem jmiClose = new JMenuItem("Close"); JMenuItem jmiSave = new JMenuItem("Save"); JMenuItem jmiExit = new JMenuItem("Exit"); jmFile.add(jmiOpen); jmFile.add(jmiClose); jmFile.add(jmiSave); jmFile.addSeparator(); jmFile.add(jmiExit); jmb.add(jmFile); // Create the Help menu. JMenu jmHelp = new JMenu("Help"); JMenuItem jmiAbout = new JMenuItem("About"); jmHelp.add(jmiAbout); jmb.add(jmHelp); // Add action listeners for the menu items. jmiOpen.addActionListener(this); jmiClose.addActionListener(this); jmiSave.addActionListener(this); jmiExit.addActionListener(this); jmiAbout.addActionListener(this); // Add the menu bar to the frame. jfrm.setJMenuBar(jmb); // Display the frame. jfrm.setVisible(true); } // Handle menu item action events. public void actionPerformed(ActionEvent ae) { // Get the action command from the menu selection. String comStr = ae.getActionCommand(); // If user chooses Exit, then exit the program. if(comStr.equals("Exit")) System.exit(0); // Otherwise, display the selection. System.out.println(comStr + " Selected"); } public static void main(String args[]) { // Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new Main(); } }); } }