Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 437
AdamOutler Avatar asked Feb 18 '12 18:02

AdamOutler


1 Answers

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();
            }
        });
    }
}
like image 54
nIcE cOw Avatar answered Nov 09 '22 16:11

nIcE cOw