Skizit
Skizit

Reputation: 44842

add JMenuBar to a JPanel?

I've got a JMenuBar and a JPanel. I'd like to add the JMenuBar to the JPanel. How would I do so?

Upvotes: 16

Views: 44758

Answers (5)

Peter Quiring
Peter Quiring

Reputation: 1706

I have another solution, although you have to add the JMenuBar in the "Other Components" in NetBeans (good enough). Create a JPanel and then add another JPanel inside (call it child) that fills the entire outter JPanel. Place your controls in the child panel. Then add the JMenuBar but NetBeans will place it in the "Other Components". Edit your source and in the ctor after it calls "initComponents" place a call to this function:

public static void setJPanelMenuBar(JPanel parent, JPanel child, JMenuBar menuBar) {
    parent.removeAll();
    parent.setLayout(new BorderLayout());
    JRootPane root = new JRootPane();
    parent.add(root, BorderLayout.CENTER);
    root.setJMenuBar(menuBar);
    root.getContentPane().add(child);
    parent.putClientProperty("root", root);  //if you need later
  }

For example, your ctor might look like this:

  public MyPanel() {
    initComponents();
    setJPanelMenuBar(this, child, myMenuBar);
  }

Works for me. Got the idea by looking at JInternalFrame source code. All it does is replace the child JPanel with a JRootPane() and then put the child into the root pane's content pane.

Upvotes: 1

user2248926
user2248926

Reputation: 1

Try putting a jDesktopPane on your panel and then add a menubar to that. I'm using a tabbed pane in my example below, but it should work the same for a panel.

    JDesktopPane desktopPane = new JDesktopPane();
    tabbedPane.addTab("New tab", null, desktopPane, null);

    JMenuBar menuBar_1 = new JMenuBar();
    menuBar_1.setBounds(0, 0, 441, 21);
    desktopPane.add(menuBar_1);

Upvotes: 0

Panday Manish Sahay
Panday Manish Sahay

Reputation: 9

I tried too but JMenuItem with Jmenu and JmenuBar was not added to JPanel. But you can get that feel if you declare JFrame's layout as null then use setBounds(x, y, width, height) on JMenuBar instance then add the menu bar to JFrame.

Upvotes: 0

Reboot
Reboot

Reputation: 1744

You can use a BorderLayout for your JPanel and put the JMenuBar into the NORTH area of the panel with

JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(menubar, BorderLayout.NORTH);

JMenuBar is a JComponent and can be added to a Container like any other JComponent.

Upvotes: 19

Codemwnci
Codemwnci

Reputation: 54884

JMenuBars are set to the JFrame using the setJMenuBar method.

See the following tutorial on how to use them.

http://download.oracle.com/javase/tutorial/uiswing/components/menu.html

Upvotes: 5

Related Questions