November 29, 2022

Menus and MenuBars

Pull-down and pop-up menus are supported by Swing. A menu bar can be associated with a top-level window. A menu bar lists all of the top-level menu options. A drop-down menu is linked with each option.

Constructors of MenuBar class

  • MenuBar():It creates a new Menu bar.
  • JMenuBar()

Public methods of Menubar class

  • Menu add(Menu m):It adds the specified menu to the menu bar.
  • Menu getMenu(int i):It gets the specified menu.
  • Int getMenuCount():It gets the number of menus on the menu bar.
  • Void remove(int index):It removes  the menu located at the  specified  index from this menu bar.
  • Void remove(MenuComponent m):It removes the specified menu component from  this menu bar.

Menu class

A pull-down menu component that is deployed from a menu bar is represented by the menu class. Within a menu, we can establish a hierarchy of submenus.

Constructors of Menu Class

  • Menu():It constructs a new menu with an empty label.
  • Menu(String label):It constructs a new menu with the specified label.
  • Menu(String label,boolean teareof):It constructs a new menu with the specified label,indicating whether the menu can be torn off.
  • JMenu()
  • JMenu(String)

 Public methods of Menu Class

  • MenuItem add(MenuItem mi):It adds the specified menu item to this menu.
  • Void addSeparator():Its adds  a separator line,or a hyphen,to the menu at the current position.
  • MenuItem getItem(int index):It gets the item located at the specified index of this menu.
  • Int getItemCount():it gets the number of items in this menu.
  • Void insert(MenuItem menuitem,int index):it inserts a menu item into this menu at the specified position.
  • Void insertSeparator(int index):it inserts a separator at the specified position.
  • Void remove(int index):It removes the menu item at the specified index from this menu.
  • Void remove(MenuComponent item):It removes the specified menu item from this menu.
  • Void removeAll():It removes all items from this menu.

MenuItem Class

The class MenuItem, or one of its subclasses, should be used to create all menu items. It comes with a simple named menu item by default.

Constructor of MenuItem class

  • MenuItem():It constructs a new menuitem with an empty label and no keyboard shortcut.
  • MenuItem(String label):It constructs a new menuitem with the specified label and no keyboard shortcut.
  • Menu(String label,MenuShortcut s):It constructs a new menu item with an associated keyboard shortcut.

Swing JMenuItem

Some of the constructor to create actual item in a menu:

  • JMenuItem()
  • JMenuItem(String text)
  • JMenuItem(Icon icn)
  • JMenuItem(String text,Icon icon)
  • JMenuItem(String text,int mnemonic)

 Public methods of MenuItem Class

  • Void deleteShortcut()
  • String getActionCommand()
  • String getLabel()
  • Boolean isEnabled()
  • Void setActionCommand(String Command)
  • Void setEnabled(boolean b)
  • Void setLabel(String label)
  • Void setShortcut(MenuShortcut s)

Examples:

package swings_2;

import javax.swing.*; 

class swingmenu 

 JMenu menu, submenu; 

 JMenuItem i1, i2, i3, i4, i5; 

 swingmenu(){ 

 JFrame f= new JFrame(“Menu and MenuItem Example”); 

 JMenuBar mb=new JMenuBar(); 

 menu=new JMenu(“Menu”); 

 submenu=new JMenu(“Sub Menu”); 

 i1=new JMenuItem(“Item 1”); 

 i2=new JMenuItem(“Item 2”); 

 i3=new JMenuItem(“Item 3”); 

 i4=new JMenuItem(“Item 4”); 

 i5=new JMenuItem(“Item 5”); 

 menu.add(i1); menu.add(i2); menu.add(i3); 

 submenu.add(i4); submenu.add(i5); 

 menu.add(submenu); 

 mb.add(menu); 

 f.setJMenuBar(mb); 

 f.setSize(400,400); 

 f.setLayout(null); 

 f.setVisible(true); 

public static void main(String args[]) 

new swingmenu(); 

}}

Output:

Menu component in Java Swing

CheckBoxMenuItem Class

The CheckboxMenuItem class represents a check box that can be found in a menu. Selecting a check box in the menu toggles the status of the control from on to off or off to on.

Constructors:

  • CheckboxMenuItem():It creates a check box menu item with an empty label.
  • CheckBoxMenuItem(label):It creates a check box menu item with specified label.
  • CheckboxMenuItem(label,boolean state):It creates a checkbox menu item with the specified label and state.

Public methods:

  • booleangetState()
  • voidsetState(boolean b)

Swing JcheckBoxMenuItem

Some of the constructor to create a check box which can be included in a menu:

  • JCheckboxMenuItem()
  • JCheckBoxMenuItem(String text)
  • JCheckboxMenuItem(Icon icn):
  • JCheckBoxMenuItem(String text, boolean state)
  • JCheckBoxMenuItem(String text,Icon icn)
  • JCheckBoxMenuItem(String text,Icon icn,boolean state)

Example:

package swings_2;

import java.awt.event.ActionEvent; 

import java.awt.event.ActionListener; 

import java.awt.event.KeyEvent; 

import javax.swing.AbstractButton;

import javax.swing.Icon; 

import javax.swing.JCheckBoxMenuItem; 

import javax.swing.JFrame; 

import javax.swing.JMenu; 

import javax.swing.JMenuBar; 

import javax.swing.JMenuItem; 

public class JavaCheckBoxMenuItem { 

 public static void main(final String args[]) { 

 JFrame frame = new JFrame(“Jmenu Example”); 

 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

 JMenuBar menuBar = new JMenuBar(); 

 // File Menu, F – Mnemonic 

 JMenu fileMenu = new JMenu(“File”); 

 fileMenu.setMnemonic(KeyEvent.VK_F); 

 menuBar.add(fileMenu); 

 // File->New, N – Mnemonic 

 JMenuItem menuItem1 = new JMenuItem(“Open”, KeyEvent.VK_N); 

 fileMenu.add(menuItem1); 

 JCheckBoxMenuItem caseMenuItem = new JCheckBoxMenuItem(“Option_1”); 

 caseMenuItem.setMnemonic(KeyEvent.VK_C); 

 fileMenu.add(caseMenuItem); 

 ActionListener aListener = new ActionListener() { 

 public void actionPerformed(ActionEvent event) { 

 AbstractButton aButton = (AbstractButton) event.getSource(); 

 boolean selected = aButton.getModel().isSelected(); 

 String newLabel; 

 Icon newIcon; 

 if (selected) { 

 newLabel = “Value-1”; 

 } else { 

 newLabel = “Value-2”; 

 } 

 aButton.setText(newLabel); 

 } 

 }; 

caseMenuItem.addActionListener(aListener); 

 frame.setJMenuBar(menuBar); 

 frame.setSize(350, 250); 

 frame.setVisible(true); 

 } 

} 

Output:

Menu component in Java Swing

Swing JRadioButtonMenuItem

The JRadioButtonMenuItem class represents a Radio Button which can be included in a menu.Selecting the Radio Button in the menu changes control’s state from on to off or fro off to on.It can be created by using following constructors:

  • JRadioButtonMenuItem()
  • JRadioButtonMenuItem(String text)
  • JRadioButtonMenuItem(Icon icn)
  • JRadioButtonMenuItem(String text,boolean state)
  • JRadioButtonMenuItem(Icon icn,boolean state)
  • JRadioButtonMenuItem(String text,Icon icn)
  • JRadioButtonMenuItem(String text,Icon icn,boolean state)

Example:

package swings_2;

import java.awt.event.KeyEvent;

import javax.swing.ButtonGroup;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JRadioButtonMenuItem;

public class RadioButtonMenuSample {

 public static void main(String args[]) {

 JFrame f = new JFrame(“JRadioButtonMenuItem Sample”);

 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 JMenuBar bar = new JMenuBar();

 JMenu menu = new JMenu(“Options”);

 menu.setMnemonic(KeyEvent.VK_O);

 ButtonGroup group = new ButtonGroup();

 JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(“North”);

 group.add(menuItem);

 menu.add(menuItem);

 menuItem = new JRadioButtonMenuItem(“East”);

 group.add(menuItem);

 menu.add(menuItem);

 menuItem = new JRadioButtonMenuItem(“West”);

 group.add(menuItem);

 menu.add(menuItem);

 menuItem = new JRadioButtonMenuItem(“South”);

 group.add(menuItem);

 menu.add(menuItem);

 menuItem = new JRadioButtonMenuItem(“Center”);

 group.add(menuItem);

 menu.add(menuItem);

 bar.add(menu);

 f.setJMenuBar(bar);

 f.setSize(300, 200);

 f.setVisible(true);

 }

}

Output:

Menu component in Java Swing

PopMenu Class

Popup menu represents a menu which can be dynamically popped up at a specified position within a component.

Swing JpopupMenu

  • JPopupMenu()
  • JPopupMenu(String text)

Example:

package swings_2;

import javax.swing.*; 

import java.awt.event.*; 

class PopupMenuExample 

 PopupMenuExample(){ 

 final JFrame f= new JFrame(“PopupMenu Example”); 

 final JLabel label = new JLabel(); 

 label.setHorizontalAlignment(JLabel.CENTER); 

 label.setSize(400,100); 

 final JPopupMenu popupmenu = new JPopupMenu(“Edit”); 

 JMenuItem cut = new JMenuItem(“File”); 

 JMenuItem copy = new JMenuItem(“Open”); 

 JMenuItem paste = new JMenuItem(“New”); 

 popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste); 

 f.addMouseListener(new MouseAdapter() { 

 public void mouseClicked(MouseEvent e) { 

 popupmenu.show(f , e.getX(), e.getY()); 

 } 

 }); 

 cut.addActionListener(new ActionListener(){ 

 public void actionPerformed(ActionEvent e) { 

 label.setText(“cut MenuItem clicked.”); 

 } 

 }); 

 copy.addActionListener(new ActionListener(){ 

 public void actionPerformed(ActionEvent e) { 

 label.setText(“copy MenuItem clicked.”); 

 } 

 }); 

 paste.addActionListener(new ActionListener(){ 

 public void actionPerformed(ActionEvent e) { 

 label.setText(“paste MenuItem clicked.”); 

 } 

 }); 

 f.add(label); f.add(popupmenu); 

 f.setSize(400,400); 

 f.setLayout(null); 

 f.setVisible(true);

 } 

public static void main(String args[]) 

 new PopupMenuExample(); 

}

Output:

Menu component in Java Swing

Examples:

package swings_2;

import java.awt.*;  

public class MenuExample  

{  

     MenuExample(){  

         Frame f= new Frame(“Menu and MenuItem Example”);  

         MenuBar mb=new MenuBar();  

         Menu menu=new Menu(“Menu”);  

         Menu submenu=new Menu(“Toolbar”);  

         MenuItem i1=new MenuItem(“New”);  

         MenuItem i2=new MenuItem(“Open”);  

         MenuItem i3=new MenuItem(“Save”);  

         MenuItem i4=new MenuItem(“Print”);  

         MenuItem i5=new MenuItem(“Done”); 

         CheckboxMenuItem tb=new CheckboxMenuItem(“Help”);

         menu.add(i1);  

         menu.add(i2);  

         menu.add(i3);  

         submenu.add(i4);  

         submenu.add(i5);

         menu.add(tb);

         menu.add(submenu);  

         mb.add(menu);  

         f.setMenuBar(mb);  

         f.setSize(400,400);  

         f.setLayout(null);  

         f.setVisible(true);  

}  

public static void main(String args[])  

{  

    new MenuExample();  

}  

}  

Output:

Menu component in Java Swing

Setting Mnemonics,Accelerator and Tooltip Text

Mnemonics and acceleration are two types of keyboard options supported by the menu. Mnemonics are a method of using the keyboard to browse the menu hierarchy and so improve program accessibility. A mnemonic is a key that allows you to choose a menu item that is already visible. In most cases, a menu item’s mnemonic is displayed by bolding the first occurrence of the mnemonic character in the menu item’s text.We can specify mnemonic for menus and menu items by using setMnemonic() method as below:

JMenu filemenu=new Jmenu(“File”);

FileMenu.setMnemonic(‘F’);

Accelerators, on the other hand, provide keyboard shortcuts for browsing the menu hierarchy without having to use the mouse.An accelerator is a key combination that selects a menu item regardless of whether it is visible or not.

JMenuItem miopen =new JMenuItem(“Open”);

miopen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,ActionEvent.ALT_MASK);;

Tooltips text are very useful because they explain to the users how to use a specific component.We use setToolTipText() method to specify the text to display in a tool tip.The text displays when the cursor lingers over the component.We can use getToolTipText() method to get the tooltip text.

Enabling and Disabling Menu

To disable  a MenuItem,use the seEnabled(boolean) method.If the argument is true,enable the ,menu item.Otherwise,disable the menu item.

Source code to demonstrate the  of Mnemonics,Accelerator , Enabling and Disabling Menu

package swings_2;

import java.awt.event.KeyEvent;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.UIManager;

public class menuEnableanddisable {

   public static void main(final String args[]) {

      JFrame frame = new JFrame(“MenuBar Demo”);

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JMenuBar menuBar = new JMenuBar();

      JMenu fileMenu = new JMenu(“File”);

      fileMenu.setMnemonic(KeyEvent.VK_F);

      menuBar.add(fileMenu);

      JMenuItem menuItem1 = new JMenuItem(“New”, KeyEvent.VK_N);

      fileMenu.add(menuItem1);

      JMenuItem menuItem2 = new JMenuItem(“Open File”, KeyEvent.VK_O);

      fileMenu.add(menuItem2);

      menuItem2.setEnabled(false);

      JMenu editMenu = new JMenu(“Edit”);

      editMenu.setMnemonic(KeyEvent.VK_E);

      menuBar.add(editMenu);

      JMenuItem menuItem3 = new JMenuItem(“Cut”, KeyEvent.VK_C);

      editMenu.add(menuItem3);

      JMenu projectMenu = new JMenu(“View”);

      projectMenu.setMnemonic(KeyEvent.VK_V);

      menuBar.add(projectMenu);

      JMenu runMenu = new JMenu(“Help”);

      runMenu.setMnemonic(KeyEvent.VK_H);

      menuBar.add(runMenu);

      menuBar.revalidate();

      frame.setJMenuBar(menuBar);

      frame.setSize(550, 350);

      frame.setVisible(true);

   }

}

Output:

Menu component in Java Swing

ToolBar

A JToolBar is a container that organizes numerous components into a row or column, usually buttons with icons. Toolbars frequently provide quick and easy access to functionality that is also available in menus. The JToolBar class in Java Swings adds a toolbar in an application. Any of the following constructors can be used to create toolbars:

  • JToolBar()
  • JToolBar(int orientation)
  • JToolBar(String title)
  • JToolBar(String title,int orientation)
  • JButton add(Action a):It adds a new JButton which dispatches the action.
  • protected void addImpl(Component comp, Object constraints, int index): If a JButton is being added, it is initially set to be disabled.
  • Void addSeparator(): It appends a separator of default size to the end of the tool bar.
  • Protected PropertyChangeListener createActionChangeListener(JButton b):It returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur, or null if the default property change listener for the control is desired.
  • protected JButton createActionComponent(Action a):Factory method which creates the JButton for Actions added to the JToolBar.
  • ToolBarUI getUI(): It returns the tool bar’s current UI.
  • Void setUI(ToolBarUI ui):It sets the L&F object that renders this component.
  • Void setOrientation(int o):It sets the orientation of the tool bar.

Example:

import java.awt.BorderLayout;  

import java.awt.Container;  

import javax.swing.JButton;  

import javax.swing.JComboBox;  

import javax.swing.JFrame;  

import javax.swing.JScrollPane;  

import javax.swing.JTextArea;  

import javax.swing.JToolBar;  

public class JToolBarExample {  

    public static void main(final String args[]) {  

        JFrame myframe = new JFrame(“JToolBar Example”);  

        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

        JToolBar toolbar = new JToolBar();  

        toolbar.setRollover(true);  

        JButton button = new JButton(“File”);  

        toolbar.add(button);  

        toolbar.addSeparator();  

        toolbar.add(new JButton(“Edit”));  

        toolbar.add(new JComboBox(new String[] { “make new”, “delete”, “change”, “Save”  }));  

        Container contentPane = myframe.getContentPane();  

        contentPane.add(toolbar, BorderLayout.NORTH);  

        JTextArea textArea = new JTextArea();  

        JScrollPane mypane = new JScrollPane(textArea);  

        contentPane.add(mypane, BorderLayout.EAST);  

        myframe.setSize(450, 250);  

        myframe.setVisible(true);  

    }  

}  

Output:

Menu component in Java Swing

Also Read: Dialog box and File Chooser

Facebook Comments