add JMenuBar to a JPanel?

后端 未结 5 457
孤城傲影
孤城傲影 2020-12-03 17:11

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

相关标签:
5条回答
  • 2020-12-03 17:51

    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

    0 讨论(0)
  • 2020-12-03 18:00

    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.

    0 讨论(0)
  • 2020-12-03 18:04

    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.

    0 讨论(0)
  • 2020-12-03 18:13

    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);
    
    0 讨论(0)
  • 2020-12-03 18:18

    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.

    0 讨论(0)
提交回复
热议问题