Create a nested menu item for inner menu items in Java

Description

The following code shows how to create a nested menu item for inner menu items.

Example


import java.awt.Container;
import java.awt.FlowLayout;
//from w  w w. j  ava 2  s  .  c o  m
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class Main extends JFrame {
  JMenuBar mb;

  JMenu fm, om, hm; // File, Options, Help

  JMenu opSubm; // Options Sub-Menu

  JMenuItem mi;

  Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());

    mb = new JMenuBar();
    setJMenuBar(mb);

    om = new JMenu("Options");
    opSubm = new JMenu("SubOptions");
    opSubm.add(mi = new JMenuItem("Alpha"));
    opSubm.add(mi = new JMenuItem("Gamma"));
    opSubm.add(mi = new JMenuItem("Delta"));
    om.add(opSubm);
    mb.add(om);

    pack();
  }
  public static void main(String[] arg) {
    Main mb = new Main();
    mb.setVisible(true);
  }
}

The code above generates the following result.

Create a nested menu item for inner menu items in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer