Mdr92
Mdr92

Reputation: 29

One JMenuBar and multiple JPanels

I have a problem with my application GUI. I would like to create one global JMenuBar and share it to other JPanels, but if i want to assign to multi JPanels i have error:

#

"The menuBar component is added to a parent component more than once.

•panelAll.add(menuBar);

•panelTask.add(menuBar);"

#

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();

    JPanel panelAll = new JPanel();
    frame.getContentPane().add(panelAll, "name_218556506364138");
    panelAll.setLayout(null);

    JMenuBar menuBar = new JMenuBar();
    menuBar.setBounds(0, 0, 795, 21);
    panelAll.add(menuBar);

    JPanel panelTask = new JPanel();
    frame.getContentPane().add(panelTask, "name_218567310779840");
    panelTask.setLayout(null);
    panelTask.add(menuBar);

    JPanel panelMyTask = new JPanel();
    frame.getContentPane().add(panelMyTask, "name_218578712986622");
    panelMyTask.add(menuBar);

    JPanel panelMySoftware = new JPanel();
    frame.getContentPane().add(panelMySoftware, "name_218590026900741");
    panelMySoftware.add(menuBar);

    JPanel panelMyDevices = new JPanel();
    frame.getContentPane().add(panelMyDevices, "name_218598029981563");
    panelMyDevices.add(menuBar);
}
}

Image

Upvotes: 0

Views: 208

Answers (1)

Martin Frank
Martin Frank

Reputation: 3454

i don't think its a good idea to add a JMenuBar into a JPanel, but if you insist...

a JMenuBar can be added only to one container, so you need to create more instances of the JMenuBar. That should work without problems if you use the command pattern.

//first instance
JMenuBar taskMenuBar = new MyJMenuBarImplementation();
JPanel panelMyTask = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_xxx");
panelMyTask.add(taskMenuBar);

//second instance
JMenuBar softwareMenuBar = new MyJMenuBarImplementation();
JPanel panelMySoftware = new JPanel();
frame.getContentPane().add(panelMySoftware, "name_yyy");
panelMySoftware.add(softwareMenuBar);

//and so on...

Upvotes: 1

Related Questions