[英]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,然后將子項放入根窗格的內容窗格中。
我也嘗試了,但JMenuItem
與Jmenu
和JmenuBar
沒有添加到JPanel
。 但是,如果將JFrame
的布局聲明為null然后在JMenuBar
實例上使用setBounds(x, y, width, height)
然后將菜單欄添加到JFrame
則可以獲得這種感覺。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.