0

Like the title suggests, I'd like to have exactly one JMenuBar used in multiple JFrame's. This however doesn't seem to work. Whenever adding the JMenuBar instance to a second JFrame makes the menu disappear from the first JFrame.

See my SSCCE:

public class MenuTest extends JPanel {
    private static final long serialVersionUID = -9209142740183347797L;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI(); 
            }
        });
    }

    private static void createAndShowGUI() {
        System.out.println("Created GUI on EDT? "+ SwingUtilities.isEventDispatchThread());

        JMenuBar bar = new JMenuBar();
        bar.add(new JMenu("Test1"));
        bar.add(new JMenu("Test2"));
        bar.add(new JMenu("Test3"));

        JFrame f = new JFrame("Swing Paint Demo 1");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MenuTest());
        f.setJMenuBar(bar);
        f.pack();
        f.setVisible(true);


        JFrame f2 = new JFrame("Swing Paint Demo 2");
        f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f2.add(new MenuTest());
        f2.setJMenuBar(bar);
        f2.pack();
        f2.setVisible(true);
    }
}

Might this be possible or is this prohibited?

Velth
  • 1,108
  • 3
  • 15
  • 29

1 Answers1

4

This can't be done, at least not the way you want to.

A component may belong to only a single parent container, this means the moment you try applying it to a second container, it will effectively remove it from the previous container.

Instead of trying to maintain a single instance, instead, consider using a "builder" or "factory" pattern which generates new instances of the JMenuBar for you.

Too make life easier, I would suggest having a look at How to Use Actions

Also have a look at The Use of Multiple JFrames, Good/Bad Practice?

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366