Java Swing How to - Add Separator to JMenu








Question

We would like to know how to add Separator to JMenu.

Answer

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
/*from w ww  .  j av  a  2  s  .  c  o  m*/
public class MenuSeparator extends JFrame {
  public MenuSeparator() {
    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"));

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

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

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