JMenuBar, JMenu, JMenuItem

MENUS 

The container for the top-level menu items is called a menu bar. In java, a menu bar is positioned inside a frame. The menu bar contains menus. A menu is a collection of menuitems and more menus (sub menus).

In order to create a menu, we have to first of all construct a menu bar and attach it to the frame.

JMenuBar menuBar = new JMenuBar( );
setJMenuBar (menuBar);

Then we shall add a menu named file to the menu bar, as follows:

JMenu menu1 = new JMenu (“File”);
menuBar.add(File);

Then we shall create a menu item named new and add to the file menu, as follows.

menu1.add(new JMenuItem(“New”));

Program

fsdfdsff



 
 
 

Program Source

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

class JMenuBarTest extends JFrame {

    JMenuBarTest()
    {
        setTitle("JMenuBar_test");
        setJMenuBarAndMenuBarItems();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    void setJMenuBarAndMenuBarItems()
    {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu1   = new JMenu("File");
        menu1.add(new JMenuItem("New"));
        menu1.add(new JMenuItem("Open"));
        menu1.add(new JMenuItem("Save"));
        menu1.add(new JMenuItem("SaveAs"));
        menu1.add(new JMenuItem("Exit"));
        JMenu menu2   = new JMenu("Edit");
        menu2.add(new JMenuItem("Cut"));
        menu2.add(new JMenuItem("Copy"));
        menu2.add(new JMenuItem("Paste"));
        menuBar.add(menu1);
        menuBar.add(menu2);
        setJMenuBar(menuBar);
    }
}

public class Javaapp {
    
    public static void main(String[] args) {
        
        JMenuBarTest jm = new JMenuBarTest();
    }
}

Leave a Comment