SWING: JMenuBar Class Cheat Sheet

Following is the declaration for javax.swing.JMenuBar class

public class JMenuBar
   extends JComponent
      implements Accessible, MenuElement

# Constructors

JMenuBar()Creates a new menu bar.

# Methods

JMenu add(JMenu c)Appends the specified menu to the end of the menu bar.
void addNotify()Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.
AccessibleContext getAccessibleContext()Gets the AccessibleContext associated with this JMenuBar.
Component getComponent()Implemented to be a MenuElement.
Component getComponentAtIndex(int i)Deprecated. Replaced by getComponent(int i)
int getComponentIndex(Component c)Returns the index of the specified component.
JMenu getHelpMenu()Gets the help menu for the menu bar.
Insets getMargin()Returns the margin between the menubar’s border and its menus.
JMenu getMenu(int index)Returns the menu at the specified position in the menu bar.
int getMenuCount()Returns the number of items in the menu bar.
SingleSelectionModel getSelectionModel()Returns the model object that handles single selections.
MenuElement[] getSubElements()Implemented to be a MenuElement. Returns the menus in this menu bar.
MenuBarUI getUI()Returns the menubar’s current UI.
String getUIClassID()Returns the name of the L&F class that renders this component.
boolean isBorderPainted()Returns true if the menu bars border should be painted.
boolean isSelected()Returns true if the menu bar currently has a component selected.
void menuSelectionChanged(boolean isIncluded)Implemented to be a MenuElement, does nothing.
protected void paintBorder(Graphics g)Paints the menubar’s border, if the BorderPainted property is true.
protected String paramString()Returns a string representation of this JMenuBar.
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)Subclassed to check all the child menus.
void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)Implemented to be a MenuElement, does nothing.
void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)Implemented to be a MenuElement, does nothing.
void removeNotify()Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.
void setBorderPainted(boolean b)Sets whether the border should be painted.
void setHelpMenu(JMenu menu)Sets the help menu that appears when the user selects the “help” option in the menu bar.
void setMargin(Insets m)Sets the margin between the menubar’s border and its menus.
void setSelected(Component sel)Sets the currently selected component, producing a change to the selection model.
void setSelectionModel(SingleSelectionModel model)Sets the model object to handle single selections.
void setUI(MenuBarUI ui)Sets the L&F object that renders this component.
void updateUI()Resets the UI property with a value from the current look and feel.

# Methods Inherited

  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

# JMenuBar Example

SwingMenuDemo.java

package com.simplecheatsheet.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.");
      }    
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *