繁体   English   中英

将JMenuBar添加到JPanel?

[英]add JMenuBar to a JPanel?

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

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

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

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

使用setJMenuBar方法将JMenuBars设置为JFrame。

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

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

尝试在面板上放置一个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);

我有另一个解决方案,虽然你必须在NetBeans的“其他组件”中添加JMenuBar(足够好)。 创建一个JPanel,然后添加另一个JPanel(称为子),填充整个outter 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,然后将子项放入根窗格的内容窗格中。

我也尝试了,但JMenuItemJmenuJmenuBar没有添加到JPanel 但是,如果将JFrame的布局声明为null然后在JMenuBar实例上使用setBounds(x, y, width, height)然后将菜单栏添加到JFrame则可以获得这种感觉。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM