SWING JMenu Class

Advertisements


Introduction

The Menu class represents pull-down menu component which is deployed from a menu bar.

Class declaration

Following is the declaration for javax.swing.JMenu class:

public class JMenu
   extends JMenuItem
      implements Accessible, MenuElement

Field

Following are the fields for java.awt.Component class:

  • protected JMenu.WinListener popupListener -- The window-closing listener for the popup.

Class constructors

S.N.Constructor & Description
1JMenu()
Constructs a new JMenu with no text.
2JMenu(Action a)
Constructs a menu whose properties are taken from the Action supplied.
3JMenu(String s)
Constructs a new JMenu with the supplied string as its text.
4JMenu(String s, boolean b)
Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or not.

Class methods

S.N.Method & Description
1JMenuItem add(Action a)
Creates a new menu item attached to the specified Action object and appends it to the end of this menu.
2Component add(Component c)
Appends a component to the end of this menu.
3Component add(Component c, int index)
Adds the specified component to this container at the given position.
4JMenuItem add(JMenuItem menuItem)
Appends a menu item to the end of this menu.
5JMenuItem add(String s)
Creates a new menu item with the specified text and appends it to the end of this menu.
6void addMenuListener(MenuListener l) Adds a listener for menu events.
7void addSeparator()
Appends a new separator to the end of the menu.
8void applyComponentOrientation(ComponentOrientation o)
Sets the ComponentOrientation property of this menu and all components contained within it.
9protected PropertyChangeListener createActionChangeListener(JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
10protected JMenuItem createActionComponent(Action a)
Factory method which creates the JMenuItem for Actions added to the JMenu.
11protected JMenu.WinListener createWinListener(JPopupMenu p)
Creates a window-closing listener for the popup.
12void doClick(int pressTime)
Programmatically performs a "click".
13protected void fireMenuCanceled()
Notifies all listeners that have registered interest for notification on this event type.
14protected void fireMenuDeselected()
Notifies all listeners that have registered interest for notification on this event type.
15protected void fireMenuSelected()
Notifies all listeners that have registered interest for notification on this event type.
16AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JMenu.
17Component getComponent()
Returns the java.awt.Component used to paint this MenuElement.
18int getDelay()
Returns the suggested delay, in milliseconds, before submenus are popped up or down.
19JMenuItem getItem(int pos)
Returns the JMenuItem at the specified position.
20int getItemCount()
Returns the number of items on the menu, including separators.
21Component getMenuComponent(int n)
Returns the component at position n.
22int getMenuComponentCount()
Returns the number of components on the menu.
23Component[] getMenuComponents()
Returns an array of Components of the menu's subcomponents.
24MenuListener[] getMenuListeners()
Returns an array of all the MenuListeners added to this JMenu with addMenuListener().
25JPopupMenu getPopupMenu()
Returns the popupmenu associated with this menu.
26protected Point getPopupMenuOrigin()
Computes the origin for the JMenu's popup menu.
27MenuElement[] getSubElements()
Returns an array of MenuElements containing the submenu for this menu component.
28String getUIClassID()
Returns the name of the L&F class that renders this component.
29JMenuItem insert(Action a, int pos)
Inserts a new menu item attached to the specified Action object at a given position.
30JMenuItem insert(JMenuItem mi, int pos)
Inserts the specified JMenuitem at a given position.
31void insert(String s, int pos)
Inserts a new menu item with the specified text at a given position.
32void insertSeparator(int index)
Inserts a separator at the specified position.
33boolean isMenuComponent(Component c)
Returns true if the specified component exists in the submenu hierarchy.
34boolean isPopupMenuVisible()
Returns true if the menu's popup window is visible.
35boolean isSelected()
Returns true if the menu is currently selected (highlighted).
36boolean isTearOff()
Returns true if the menu can be torn off.
37boolean isTopLevelMenu()
Returns true if the menu is a 'top-level menu', that is, if it is the direct child of a menubar.
38void menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this menu.
39protected String paramString()
Returns a string representation of this JMenu.
40protected void processKeyEvent(KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.
41void remove(Component c)
Removes the component c from this menu.
42void remove(int pos)
Removes the menu item at the specified index from this menu.
43void remove(JMenuItem item)
Removes the specified menu item from this menu.
44void removeAll()
Removes all menu items from this menu.
45void removeMenuListener(MenuListener l)
Removes a listener for menu events.
46void setAccelerator(KeyStroke keyStroke)
setAccelerator is not defined for JMenu.
47void setComponentOrientation(ComponentOrientation o)
Sets the language-sensitive orientation that is to be used to order the elements or text within this component.
48void setDelay(int d)
Sets the suggested delay before the menu's PopupMenu is popped up or down.
49void setMenuLocation(int x, int y)
Sets the location of the popup component.
50void setModel(ButtonModel newModel)
Sets the data model for the "menu button" -- the label that the user clicks to open or close the menu.
51void setPopupMenuVisible(boolean b)
Sets the visibility of the menu's popup.
52void setSelected(boolean b)
Sets the selection status of the menu.
53void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:

  • javax.swing.JAbstractButton

  • javax.swing.JComponent

  • java.awt.Container

  • java.awt.Component

  • java.lang.Object

JMenu Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >

SwingMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class SwingMenuDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel; 

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}

Compile the program using command prompt. Go to D:/ > SWING and type the following command.

D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo

Verify the following output. (Click on File Menu.)

SWING JMenu

Advertisements
Advertisements