In NetBeans how do I add a jMenuBar to a JPanel?

AdamOutler picture AdamOutler · Feb 18, 2012 · Viewed 14.4k times · Source

I am having problems and I don't really understand why. I have a JFrame and a JPanel and everything works properly. I am trying to add a jMenuBar into the JPanel and I cannot get it to show up. It is being placed under "Other Components" and does not show up during runtime. any suggestions?

edit: It seems that the appropriate answer is NetBeans cannot add a JMenu to a JFrame. I wanted to add this to the first post because the appropriate answer below was down-voted.

Answer

nIcE cOw picture nIcE cOw · Feb 18, 2012

JMenuBar is added to the JFrame by using setJMenuBar(...) method.

Small code to help your cause :

import javax.swing.*;

public class MenuBarTest extends JFrame
{
    public MenuBarTest()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel contentPane = new JPanel();
        contentPane.setBackground(java.awt.Color.WHITE);
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        JMenuItem menuItem = new JMenuItem("Open");

        menu.add(menuItem);
        menuBar.add(menu);

        setContentPane(contentPane);
        setJMenuBar(menuBar);
        setSize(200, 200);
        setVisible(true);
    }

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