簡體   English   中英

無法將JMenuBar添加到擴展JFrame

[英]Trouble adding JMenuBar to extended JFrame

我的Main類擴展了JFrame ,由於某種原因,我無法正確顯示MenuBar和項目。 有添加菜單欄的特殊方法嗎?

public class Main extends JFrame
{
// DRIVER
public static void main(String[] args) 
{
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Main window = new Main();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}

private JMenuBar menuBar; 

private JMenu menu,
          menuFile;

private JMenuItem menuItemNew,
              menuItemExit;
...

// CONSTRUCTOR
public Main()
{

    initializeWindow();
    initializeMenu();
}

private void initializeWindow()
{
    setTitle(TITLE + " " + VERSION);
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    setBackground(Color.DARK_GRAY);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    backgroundColor = new GradientBackground(WINDOW_WIDTH, WINDOW_HEIGHT);
}

private void initializeMenu()
{
    // Menubar
    menuBar = new JMenuBar();
    menuBar.setBounds(0, 0, WINDOW_WIDTH, 72);
    menuBar.setBackground(Color.LIGHT_GRAY);
    menuBar.setVisible(true);
    setJMenuBar(menuBar);

    // Menu title
    menu = new JMenu();
    menu.setForeground(Color.BLACK);
    menuBar.add(menu);



    // File Option
    menuFile = new JMenu("FILE");
    menuFile.setForeground(Color.BLACK);
    menuFile.setBackground(Color.DARK_GRAY);
    menuBar.add(menuFile);

    // New File
    menuItemNew = new JMenuItem("New");
    menuItemNew.setForeground(Color.BLACK);
    menuItemNew.setBackground(Color.DARK_GRAY);
    menuFile.add(menuItemNew);

    // New File
    menuItemExit = new JMenuItem("Exit");
    menuItemExit.setForeground(Color.BLACK);
    menuItemExit.setBackground(Color.DARK_GRAY);
    menuItemExit.setEnabled(true);
    menuFile.add(menuItemExit);

    getContentPane().add(menuBar);
} // END initializeMenu()
  • 我認為您正在尋找JFrame.setMenuBar而不是add(JMenuBar)

  • Java 5和更高版本沒有必需的getContentPane()

  • 不要擴展JFrame ,將此Object創建為local variable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM