Search code examples
javaswingjmenuitem

How to Set Vertical Separators for JMenuItems


I can only set horizontal separator to my code , how to set vertical one ? Similar to this http://jade-cheng.com/hpu/2012-spring/csci-2912/assignment-5/blueprint-2.png

    file.add(newMenuItem);
    file.add(openMenuItem);
    file.add(saveMenuItem);
    file.add(subMenu);
    file.addSeparator();
    file.add(exitMenuItem);

Solution

  • Vertical separator in JMenuItem? The only thing which comes to my mind and which you can treat as a JSeparator is something like below:

    enter image description here

    But this left "JSeparator" is not an extra added JSeparator, but depends on LookAndFeel.

    Below you see the same JFrame with the same JMenuBar but with different lookandfeel:

    enter image description here

    The code for both screens is exactly the same, but executed with different look and feels:

    public class NewClass extends JFrame {
    
        public NewClass() throws HeadlessException {
            JMenuBar menuBar = new JMenuBar();
            JMenu menu = new JMenu("File");
            menuBar.add(menu);
            menu.add(new JMenuItem("Open..."));
            menu.add(new JMenuItem("Save"));
            menu.add(new JMenuItem("Save as..."));
            menu.addSeparator();
            menu.add(new JMenuItem("Delete"));
    
            setJMenuBar(menuBar);
            setSize(new Dimension(500,500));
            setVisible(true);
        }
    
        public static void main(String[] args) {
            try {
               //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
               //UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
               UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());      
               new NewClass();
            } catch (ClassNotFoundException ex) {
              Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
              Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
              Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedLookAndFeelException ex) {
              Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
            }
        }   
    }
    

    Note, that

    menu.add(new JSeparator(JSeparator.VERTICAL));
    

    will not generate any separator at all (you can try)