2016-03-05 250 views
0

我正在學習使用java編程的GUI,並嘗試修改現有程序以在框架頂部添加新的菜單欄。學習Java GUI -

主要方法如下。 MainPanel類擴展JPanel幷包含程序的主要組件(一個基本遊戲)。

public static void main(String[] args) { 
     JFrame frame = new JFrame("Sokuban"); 
     MainPanel panel = new MainPanel(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new BorderLayout()); 
     frame.setContentPane(panel); 
     frame.pack(); 
     frame.setVisible(true); 

} 

我不知道我是否應該添加一個新JPanel,將其添加到JFrame,然後內的添加按鈕?或者在現有面板或框架內創建一個JMenuBar,然後使用BorderLayout.NORTH進行排列?

只是玩弄的東西我對谷歌發現,我已經分開審訊以下片段(還沒有把所有的代碼):

JMenuBar menuBar = new JMenuBar(); 

frame.add(new Button("Button"), BorderLayout.SOUTH); 

panel.BorderLayout.SOUTH; 

JPanel frame2 = new JPanel(); 
    window.add(frame2, BorderLayout.NORTH); 
    JButton b1 = new JButton(); 
    frame2.setSize(500,500);  
    b1.setSize(400,400); 
    b1.setVisible(true); 
    b1.setText("Button"); 
    frame2.add(b1); 
    frame2.setVisible(true); 

我不知道我應該去哪個方向。任何指針非常感謝!

+2

看看[如何使用菜單](https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html)。 –

回答

1

不要那樣做,看看這個是你在找什麼

這個鏈接是一個JMenuBar的 https://docs.oracle.com/javase/7/docs/api/java/awt/MenuBar.html

這個鏈接是JMenu的https://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html

此鏈接是的JMenuItem https://docs.oracle.com/javase/7/docs/api/javax/swing/JMenuItem.html

您不需要新的JFrame來創建菜單,您可以使用JMenuBar();

JMenuBar myMenu = new JMenuBar(); 
//The above snippet does not create or add menus it's simply the container that holds them 

JMenu fileMenu = new JMenu("File"); // This will create a menu named file 

JMenuItem openChoice = new JMenuItem("Open"); /* This will create an option under 
the fileMenu named open*/ 

//To Actually add these things you would do this 
    setJMenuBar(myMenu); 
    myMenu.add(fileMenu); // This adds fileMenu to the menubar 
    fileMenu.add(openChoice); // This adds openChocie to the JMenu named fileOption 

現在上面的代碼是一個非常簡單的例子,以我如何設置菜單sugesst我概括這裏的代碼之後,你要學會在這個改善,因爲這是隻爲你一個起點!

+0

非常感謝!剛剛設法創建(非常基本!)一個:) – javapalava

+0

很高興我能幫助:) – Afflicted

1

我不確定是否應該添加一個新的JPanel,將它添加到JFrame中,然後在該添加按鈕中?或者在現有面板或框架內創建一個JMenuBar,然後使用BorderLayout.NORTH進行排列?

這裏有一些個人的經驗,我可以與大家分享:

我通常會先規劃我的用戶界面的外觀(無論是在我的腦海裏在紙上)。之後,爲容器決定合適的佈局管理器

如果UI很複雜,我可以使用多於一個佈局的嵌套面板。但最終,我通常會有一個主面板,其中包含所有其他組件(子面板/按鈕/ textFields ..)。

將主面板添加到JFrame中。 (你可以有一個自定義的JPanel,而且我們很少需要一個定製的JFrame)。


至於菜單欄:

  • 添加的JMenuItem到JMenu的
  • 添加JMenu的到的JMenuBar
  • 使用frame.setJMenuBar(menuBar);

添加的JMenuBar的框架下圖像應該可以幫助你理解分層CHY:

enter image description here