Search code examples
javaswingjframejmenubarnull-layout-manager

JMenuBar doesn't show


I am trying to create a Menubar, but for some reason it doesn't show up. Google research did not help. I put setVisible(true) at the end, I added the Menubar to the window and I added Menupoints into the bar as well. However it still doesn't show up.

public MusicPlayerGUI(){
        setLayout(null);
        
        getContentPane().setBackground(Color.green);
        setTitle("MusicPlayer");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(600,700);
        
        initComponent();
        add(bar);
        add(edit);
        add(show);
        add(createPlaylist);
        add(addSong);
        add(all);
        add(genre);
        add(rock);
        add(indie);
        add(playlists);
    
        setVisible(true);
    }
    
    public void initComponent() {
        //Menubar
        bar = new JMenuBar();
        setJMenuBar(bar);
        edit = new JMenu("Edit");
        bar.add(edit);
        show = new JMenu("Show");
        bar.add(show);
        createPlaylist = new JMenuItem("Create new Playlist");
        edit.add(createPlaylist);
        addSong = new JMenuItem("Add new Song");
        edit.add(addSong);
        all = new JMenuItem("All");
        show.add(all);
        genre = new JMenuItem("Genre");
        show.add(genre);
        rock = new JMenuItem("Rock");
        genre.add(rock);
        indie = new JMenuItem("Indie");
        genre.add(indie);
        playlists = new JMenuItem("Playlists");
        show.add(playlists);
        
        
    }
    

Solution

  • In initComponent() you use:

    setJMenuBar(bar);
    

    which is correct.

    But then in your constructor you attempt to add the "bar" to the frame again:

        initComponent();
        add(bar); // delete this line
    

    Which removes the menubar from the reseverd area of the frame. And because you are using a null layout and the "bar" has a size of (0, 0) by default there is nothing to paint.

    1. a component can only have a single parent, don't attempt to add the component twice.

    2. Don't use a null layout. Swing was designed to be used with layout managers.