16

我有一个 JMenuBar 和一个 JPanel。我想将 JMenuBar 添加到 JPanel。我该怎么做?

4

5 回答 5

19

您可以为您的 JPanel 使用BorderLayout并将 JMenuBar 放入面板的 NORTH 区域

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

JMenuBar 是一个 JComponent,可以像任何其他 JComponent 一样添加到容器中。

于 2010-11-29T00:11:05.187 回答
4

JMenuBars 使用 setJMenuBar 方法设置为 JFrame。

请参阅以下教程了解如何使用它们。

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

于 2010-11-28T23:55:16.613 回答
0

我有另一个解决方案,尽管您必须在 NetBeans 的“其他组件”中添加 JMenuBar(足够好)。创建一个 JPanel,然后在内部添加另一个 JPanel(称为子),填充整个外部 JPanel。将控件放在子面板中。然后添加 JMenuBar,但 NetBeans 会将其放在“其他组件”中。编辑您的源代码并在调用“initComponents”后在 ctor 中调用此函数:

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
  }

例如,您的 ctor 可能如下所示:

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

为我工作。通过查看 JInternalFrame 源代码得到了这个想法。它所做的只是用 JRootPane() 替换子 JPanel,然后将子 JPanel 放入根窗格的内容窗格中。

于 2015-03-24T00:19:00.890 回答
0

尝试在您的面板上放置一个 jDesktopPane,然后向其中添加一个菜单栏。我在下面的示例中使用了一个选项卡式窗格,但它对于面板的工作方式应该相同。

    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);
于 2013-04-05T11:58:25.723 回答
0

我也尝试过,但JMenuItem没有Jmenu添加JmenuBarJPanel. 但是,如果您将JFrame布局声明为 null 然后setBounds(x, y, width, height)JMenuBar实例上使用然后将菜单栏添加到JFrame.

于 2011-03-10T13:19:15.467 回答