Java Swing | Menu Bar Example
To create menus, we need to follow the following steps:
- First, A JMenubar is created
- Then, we attach all of the menus to this JMenubar.
- Then we add JMenuItem to the JMenu.
- The JMenubar is then added to the frame by using setJMenuBar() method.
JMenuBar
We can create menu bar by using following constructor:
JMenuBar()
JMenu
It can be created by using following constructors:
JMenu()
JMenu(String)
import javax.swing.*; class Menu extends JFrame{ JMenuBar mb; JMenu file, edit, data, name; JMenuItem open, save, sas, cut, copy, paste; JCheckBoxMenuItem raju, indra; Menu(){ setTitle("Menu Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mb=new JMenuBar(); file=new JMenu("File"); edit=new JMenu("Edit"); data=new JMenu("Data"); name=new JMenu("Name"); open=new JMenuItem("Open"); save=new JMenuItem("Save"); sas=new JMenuItem("Save As"); cut=new JMenuItem("Cut"); copy=new JMenuItem("Copy"); paste=new JMenuItem("Paste"); raju=new JCheckBoxMenuItem("Raju"); indra=new JCheckBoxMenuItem("Indra"); file.add(open); file.add(save); file.add(sas); edit.add(cut); edit.add(copy); edit.add(paste); data.add(name); name.add(raju); name.add(indra); mb.add(file); mb.add(edit); mb.add(data); setJMenuBar(mb); setSize(500, 500); setVisible(true); } public static void main(String args[]){ new Menu(); } }