Question

I am trying to get my JMenuBar to display in the GUI, however it just appears as a 1-pixel line at the top.

This is my code...

public LibraryView() {
    setBounds(100,100,640,480);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());

    JMenuBar b1 = new JMenuBar();
    JMenu m1 = new JMenu("Test");
    JMenuItem i1 = new JMenuItem("Item1");

    this.setJMenuBar(b1);
}

Could someone please help me to understand what is wrong.

Was it helpful?

Solution

You need to add the JMenu and JMenuItem to the JMenuBar. You also need to pack() and setVisible(true); at the end of the method, just before the GUI is shown...

public LibraryView() {
    setBounds(100,100,640,480);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());

    JMenuBar b1 = new JMenuBar();
    JMenu m1 = new JMenu("Test");
    JMenuItem i1 = new JMenuItem("Item1");

    m1.add(i1); // ADDED
    b1.add(m1); // ADDED

    this.setJMenuBar(b1);

    pack(); // ADDED
    setVisible(true); // MOVED
}

OTHER TIPS

You should call setVisible(true) only after adding all components to the top level window. Also don't forget to use layout managers, to let these managers and your component's preferredSize set the sizes of components, and don't forget to call pack().

call repaint() right before you call set visible(true) this NEVER FAILS.

 setJMenuBar(menuBar);
 menuBar.add(jMenuItem);
 repaint(); //then
 setVisible(true); //Assured NEVER FAILS
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top