Using JMenu

Guest Posts Steven


In this article I'm going to explain how to create a menu in your program.

A menu in java needs 3 things:

  • JMenuBar: which is the object that allows to hold your different options in your menu.

  • JMenu: A JManu is a popup window containing items that is displayed when the user selects an option on the JMenuBar.
  • JMenuItem: A menu item is essentially a button sitting in a list on a JMenu. When the user selects the "button", the action associated with the menu item is performed.

Here's the code:

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

public class exampleJFrame extends JFrame{
   private JPanel _panel;
   * Create the frame.
   public exampleJFrame() {
      setVisible(true); //we make the window visible
      setResizable(false); // if write false, you won't be able to resize the window
      setTitle("Example"); //you set the title for the window
      setLocationRelativeTo(null); // you make the window appear at the center of the screen
      setSize(370,226); // you set the size of the window
      _panel = new JPanel();
      JMenuBar menuBar = new JMenuBar(); // you create the main menu bar that contains all the options
      menuBar.setBounds(0, 0, 364, 21);
      _panel.add(menuBar); // you add the bar to the frame
      JMenu mnFile = new JMenu("File"); // you add the options to the manu bar
      menuBar.add(mnFile); /// you add the option to the bar
      JMenuItem mntmOpen = new JMenuItem("Open"); // you add the items to the menus
      mnFile.add(mntmOpen); // you add the item to the menu
      JMenu mnEdit = new JMenu("Edit"); // you add the options to the manu bar
      JMenuItem mntmUndo = new JMenuItem("Undo"); // you add the items to the menus
      JMenuItem mntmRedo = new JMenuItem("Redo"); // you add the items to the menus
      JMenu mnAction = new JMenu("Action")
      JMenuItem mntmJoptionpane = new JMenuItem("JOptionPane");
      mntmJoptionpane.addActionListener(new ActionListener() { // we add an action listener to the JMenuItem
      public void actionPerformed(ActionEvent e) {
         JOptionPane.showMessageDialog(null, "You clicked a JMenuItem", "JMenu", JOptionPane.PLAIN_MESSAGE);

 public static void main(String[] args) {
    exampleJFrame example=new exampleJFrame();


The result would be:

1. You open the window:



2. You click on the JMenu "Action"



3. And then you click in the JMenuItem "JOptionPane"




As you can see you can have multiple options in your menu, and of course you can add action listeners for the items just as I did.