Java Swing Tutorial - Java JMenu.add(Component c, int index)








Syntax

JMenu.add(Component c, int index) has the following syntax.

public Component add(Component c,  int index)

Example

In the following code shows how to use JMenu.add(Component c, int index) method.

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
/*  ww w . j  a  va2s.c om*/
public class Main extends JFrame {
  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar bar = new JMenuBar();
    JMenu menu = new JMenu("File");
    bar.add(menu);

    menu.add(new JMenuItem("Close"));
    menu.add(new JSeparator()); // SEPARATOR
    menu.add(new JMenuItem("Exit"),0);

    setJMenuBar(bar);
    add(new JLabel("A placeholder"));

    pack();
    setSize(300, 300);
    setVisible(true);
  }

  public static void main(String arg[]) {
    new Main();
  }
}