java JMenuBar不可见?为什么?

java JMenuBar不可见?为什么?,java,swing,jmenubar,Java,Swing,Jmenubar,我不明白为什么我的菜单栏不可见。我有以下代码: //主要 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class Menu extends JFrame{ public static void main(String[] args){ JFrame frame = new JFrame(); fra

我不明白为什么我的菜单栏不可见。我有以下代码:

//主要

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Menu extends JFrame{
    public static void main(String[] args){

        JFrame frame = new JFrame();
        frame.setSize(500,350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        menuBar mbObj = new menuBar();

        mbObj.menuBar(frame);
    }
}
//菜单栏类

public class menuBar{

        private JMenu file,edit;
        private JMenuItem nFile ,oFile,sFile,saFile,exit;
        private JMenuItem undo,copy,paste;
        private JMenuBar bar;

        public void menuBar(JFrame frame){
            bar = new JMenuBar();
            frame.setJMenuBar(bar);
            bar.setVisible(true);
            file = new JMenu("File");
            edit = new JMenu("Edit");
            bar.add(file);
            bar.add(edit);
        }    
 }
在顶层窗口上调用
setVisible(true)
,这里是一个JFrame,仅在添加所有组件(包括
JMenuBar
后调用。您还希望避免对任何内容调用
setSize(…)
,而是在添加所有组件之后和调用
setVisible(true)
之前,使用布局管理器并在JFrame上调用
pack()

因此,顺序应该是:

// create JFrame
JFrame frame = new JFrame("Foo");

// here add all components to the JFrame
// .....
// done adding components

frame.pack();
// frame.setLocationRelativeToPlatform(true); // if you wish
frame.setVisible(true);
作为旁白,类名称应该以大写字母开头,并且不要有与类名称完全相同的方法,因为这会创建一个“伪”构造函数,并且会混淆所有人。

。现在一切正常