JMenu
JMenu class is used to put drop down menu on the window or frame. Object of MenuItem class is placed on the JMenu. JMenu object is added to the JMenuBar object.
import javax.swing.*; class MenuExample { JMenu menu,menu2, submenu; JMenuItem i1, i2, i3, i4, i5,i6; MenuExample(){ JFrame f= new JFrame("Menu and MenuItem Example"); JMenuBar mb=new JMenuBar(); menu=new JMenu("File"); submenu=new JMenu("Out"); i1=new JMenuItem("Open"); i2=new JMenuItem("Save"); i3=new JMenuItem("Save As"); i4=new JMenuItem("Exit"); menu.add(i1); menu.add(i2); menu.add(i3); submenu.add(i4); menu.add(submenu); mb.add(menu); menu2 = new JMenu("Help"); i6 = new JMenuItem("About Us"); menu2.add(i6); mb.add(menu2); f.setJMenuBar(mb); f.setSize(400,400); f.setLayout(null); f.setTitle("JMenu"); f.setLocationRelativeTo(null); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String args[]) { new MenuExample(); } }
Event handling with JMenu
import javax.swing.*; import java.awt.*; import java.awt.event.*; class MenuExample_event implements ActionListener { JMenu menu,menu2, submenu; JMenuItem i1, i2, i3, i4, i5,i6; JLabel output; MenuExample_event(){ JFrame f= new JFrame("Menu and MenuItem Example"); JMenuBar mb=new JMenuBar(); menu=new JMenu("File"); submenu=new JMenu("Out"); i1=new JMenuItem("Open"); i2=new JMenuItem("Save"); i3=new JMenuItem("Save As"); i4=new JMenuItem("Exit"); output = new JLabel("Selected: "); menu.add(i1); menu.add(i2); menu.add(i3); submenu.add(i4); menu.add(submenu); mb.add(menu); menu2 = new JMenu("Help"); i6 = new JMenuItem("About Us"); menu2.add(i6); mb.add(menu2); f.setJMenuBar(mb); f.setSize(400,400); f.setLayout(new FlowLayout()); f.setTitle("JMenu"); f.setLocationRelativeTo(null); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(output); i1.addActionListener(this); } public void actionPerformed(ActionEvent aaee){ output.setText("Open Menu is Selected!!!"); } public static void main(String args[]) { new MenuExample_event(); } }