Saturday, 31 January 2015

How to create Simple Jmenu bar JMenuItem in java

A top level window can have a menu bar associated with it.A menu bar displays list of choices associated with drop-down menu.A menu bar contains a list of MenuItem.

STEPS FOR CREATING MENU BAR:

Following are the steps for creating menubar 
  1. Set up menubar.
  2. Add menu in menubar and give it name be setText.
  3. Add menuitem in menu and give it name by setText.

JMENUBAR()

As you can see in the following program that we have used this constructor the reason of using this constructor is that creates a menubar.

JMenu()

This method is used to creates a menu item at the end of menu bar .

JMenuItem()

This method can be used to create sub menu with in a menu of menu bar.

CODING:

import javax.swing.*;
import java.awt.*;

class myjframe1 extends JFrame
 {
JMenuBar menuBar = new JMenuBar();
JMenu firstmenu = new JMenu();
JMenu secmenu = new JMenu();
JMenu submenu = new JMenu();
JMenuItem firstitem = new JMenuItem();
JMenuItem secitem = new JMenuItem();
JMenuItem thirditem = new JMenuItem();
JMenuItem subitem = new JMenuItem();
public myjframe1() 
{

setTitle("Menu Bar Example example");
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);        
setJMenuBar(menuBar);
menuBar.setPreferredSize(new Dimension(150,50));
menuBar.add(firstmenu);
menuBar.add(secmenu);
firstmenu.setText("First Menu");
secmenu.setText("second Menu");
firstmenu.add(firstitem);
firstitem.setText("First Item");
firstmenu.add(secitem);
secitem.setText("Second Item");
firstmenu.add(thirditem);
thirditem.setText("Third Item");
firstmenu.add(submenu);
submenu.setText("SUB Menu");
submenu.add(subitem);
subitem.setText("Sub Item");


}
}
class men
{
public static void main(String args[])
{
myjframe1 x= new myjframe1();
}
}

OUTPUT:


1 comment: