Search code examples
javaswingjmenu

Java GUI menu bar not showing


Any idea why the menu bar menuBar is not showing? everything looks fine to me.

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class mySticky extends JFrame implements ActionListener{

    //weStart!

    JFrame frame = new JFrame("Sticky Note");
    JMenuBar menuBar = new JMenuBar();

    JMenu noteMenu = new JMenu("Note");
    JMenuItem newNote = new JMenuItem("New Note");
    JMenuItem open = new JMenuItem("Open");
    JMenuItem saveAs = new JMenuItem("Save As");
    JMenuItem save = new JMenuItem("Save");

    //Constructor

    public mySticky(){

        setSize(400,300);
        setLocation(500,250);
        setTitle("Sticky Note");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        menuBar.add(noteMenu);

        noteMenu.add(newNote);
        noteMenu.add(open);
        noteMenu.add(saveAs);
        noteMenu.add(save);
        frame.setJMenuBar(menuBar);            
    }

    public void actionPerformed (ActionEvent e){           

    }


    public static void main (String [] args ){

        mySticky sticky = new mySticky ();
        sticky.setVisible(true);

    }
}

Solution

  • You add the menubar to frame, which is never added to any UI. Replace

    frame.setJMenuBar(menuBar);
    

    by

    setJMenuBar(menuBar);
    

    and your menubar will become visible. Or you should add frame to the UI as well. Not sure what you tried to achieve.

    And you should wrap the code of your main method in a Runnable and execute it on the EDT (for example using EventQueue.invokeLater)