add JMenuBar to a JPanel?

41,325

Solution 1

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.

Solution 2

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

Share:
41,325
Skizit
Author by

Skizit

Hi!

Updated on March 24, 2020

Comments

  • Skizit
    Skizit over 4 years

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

  • Skizit
    Skizit over 13 years
    It's not possible to add them direct to a JPanel? I've got other items on there... if I add a JFrame wont it draw over my Panel items?
  • Codemwnci
    Codemwnci over 13 years
    Well, a JMenuBar is just another JComponent, so you can add it to your JPanel just like you would anything else. However, as it is designed to be attached to a JFrame, it may not work correctly (or even at all!)
  • Enrique
    Enrique over 13 years
    I thought you can only add JMenuBar's to JFrame's
  • Skizit
    Skizit over 13 years
    Works, won't allow me to add it to the very top but close enough!
  • kleopatra
    kleopatra about 11 years
    hmm ... why a JDesktopPane?
  • Admin
    Admin about 11 years
    I'm building an app where I want to have a menubar in each detachable tab to display multiple World Wind views. This seemed like a good way to do it. Couldn't find any other way to have a separate menubar for each window.
  • Mike Bonnell
    Mike Bonnell over 10 years
    BorderLayout.PAGE_START seemed to put it at the top for me.
  • Alde
    Alde over 5 years
    Is this code outdated? This does not work any more.
  • mike3996
    mike3996 almost 3 years
    Works perfectly well.
  • Stefan Reich
    Stefan Reich over 2 years
    What's the advantage of using a JRootPane?