我有一个 JMenuBar 和一个 JPanel。我想将 JMenuBar 添加到 JPanel。我该怎么做?
5 回答
您可以为您的 JPanel 使用BorderLayout并将 JMenuBar 放入面板的 NORTH 区域
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(menubar, BorderLayout.NORTH);
JMenuBar 是一个 JComponent,可以像任何其他 JComponent 一样添加到容器中。
JMenuBars 使用 setJMenuBar 方法设置为 JFrame。
请参阅以下教程了解如何使用它们。
http://download.oracle.com/javase/tutorial/uiswing/components/menu.html
我有另一个解决方案,尽管您必须在 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 放入根窗格的内容窗格中。
尝试在您的面板上放置一个 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);
我也尝试过,但JMenuItem
没有Jmenu
添加JmenuBar
到JPanel
. 但是,如果您将JFrame
布局声明为 null 然后setBounds(x, y, width, height)
在JMenuBar
实例上使用然后将菜单栏添加到JFrame
.