java JMenuBar not visible? Why?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 12:12:26

问题


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:


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.



来源:https://stackoverflow.com/questions/25147632/java-jmenubar-not-visible-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!