javaswingjmenujmenuitemjseparator

Java Swing JSeparator in Menu incorrectly placed


I have a problem when i want insert a separator with JSeparator for Java Swing application. In point of fact, I have this problem just when i run my program on Mac, i haven't it on windows or linux. The separator is incorrectly placed, the text is strikethrough. Does anyone know why?

My code :

JMenuItem fileItem = new JMenuItem("Close");
KeyStroke ...
fileItem.add(new JSeparator(JSeparator.HORIZONTAL),BorderLayout.LINE_START);

Screenshot : enter image description here


Solution

  • Basically your code right now shows that you are assuming JMenuItem has a default BorderLayout, which could be true (but I dont think so).

    Though the root problem is you are adding the JSeparator to the JMenuItem when in fact you should add it to the JMenu which contains the various JMenuItems via JMenu#addSeparator(). See How to Use Separators for more.

    You should be doing something like:

    JMenu menu=new JMenu();
    
    JMenuItem item1=new JMenuItem("something 1");
    JMenuItem item2=new JMenuItem("something 1");
    
    menu.add(item1);
    menu.addSeparator();//lets add that separator
    menu.add(item2);
    

    giving you something like:

    enter image description here

    UPDATE:

    Here is an example:

    enter image description here

    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.SwingUtilities;
    
    public class Test {
    
        public Test() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
            JMenuBar menuBar=new JMenuBar();
    
            JMenu menu = new JMenu("File");
            JMenu menu2 = new JMenu("Else");
    
            JMenuItem item1 = new JMenuItem("something 1");
            JMenuItem item2 = new JMenuItem("something 2");
            JMenuItem item3 = new JMenuItem("else 1");
            JMenuItem item4 = new JMenuItem("else 2");
    
            menu2.add(item3);
            menu2.addSeparator();//lets add that separator
            menu2.add(item4);
    
            menu.add(menu2);
            menu.add(item1);
            menu.addSeparator();//lets add that separator
            menu.add(item2);
    
            menuBar.add(menu);
    
            frame.setJMenuBar(menuBar);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String args[]) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Test();
                }
            });
        }
    }