java JMenuBar not visible? Why?

2019-08-05 10:33发布

I cannot figure out why my menu bar isn't visible. I have following code:

//Main

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

//Menu Bar class

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

1条回答
forever°为你锁心
2楼-- · 2019-08-05 11:00

Call setVisible(true) on the top-level window, here a JFrame, only after adding all components, including the JMenuBar. You will also want to avoid calling setSize(...) on anything, and instead use layout managers and call pack() on the JFrame after adding all components and before calling setVisible(true).

So the order should be:

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

As an aside class names should begin with an upper case letter, and dont have methods with the exact same name as the class, as that creates a "pseudo"-constructor and will confuse everyone.

查看更多
登录 后发表回答