2010-11-28 116 views

回答

13

您可以使用您的JPanel一個BorderLayout,把JMenuBar的到面板的北部地區與

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

JMenuBar的是一個JComponent,可以添加到一個容器像任何其他JComponent的。

+3

我以爲只能將JMenuBar添加到JFrame的 – Enrique 2010-11-29 00:55:08

+0

Works中,不會允許我將它添加到最頂層但足夠接近! – Skizit 2010-11-29 12:10:04

4

使用setJMenuBar方法將JMenuBars設置爲JFrame。

有關如何使用它們,請參閱以下教程。

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

+0

將它們直接添加到JPanel是不可能的?我還有其他項目...如果我添加一個JFrame不會畫我的面板項目? – Skizit 2010-11-29 00:01:26

+2

那麼,JMenuBar只是另一個JComponent,所以你可以像你其他任何東西一樣將它添加到JPanel中。但是,因爲它被設計爲連接到JFrame,所以它可能無法正常工作(甚至根本不可能) – Codemwnci 2010-11-29 00:07:17

0

我也試過,但JMenuItemJmenuJmenuBar未被添加到JPanel。 但是,如果您將JFrame的佈局聲明爲空,那麼可以使用setBounds(x, y, width, height)JMenuBar實例,然後將菜單欄添加到JFrame

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); 
0

我有另一種解決方案,雖然你必須添加JMenuBar在NetBeans中的「其他組件」(足夠好)。創建一個JPanel,然後添加另一個JPanel(稱爲它的子節點),填充整個outter JPanel。將您的控件放置在子面板中。然後添加JMenuBar,但NetBeans將它放在「其他組件」中。編輯源,並在構造函數調用後「的initComponents」的地方,這個函數的調用:

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 
    } 

例如,您的構造函數可能是這樣的:

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

爲我工作。通過查看JInternalFrame源代碼獲得了這個想法。它所做的只是用JRootPane()替換子JPanel,然後將子項放入根窗格的內容窗格中。