JMenuBar not showing

user1450466 picture user1450466 · Jun 12, 2012 · Viewed 10.2k times · Source

I seem to have done everything correct. I just need to implement a simple JMenuBar but it seems to be not working. Can someone please help me out in this?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class swing {
   public static void main (String[] args) {
      JFrame frame = new JFrame ("menu");
      frame.setVisible (true);
      frame.setSize (400, 400);
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      JMenuBar bar = new JMenuBar ();
      frame.setJMenuBar (bar);
      bar.setVisible (true);
      JMenu file = new JMenu ("File");
      bar.add (file);
      JMenuItem open = new JMenuItem ("open");
      file.add(open);
   }
}

Answer

Harry Joy picture Harry Joy · Jun 12, 2012

What you are doing is displaying frame first and then add menu bar to it. It will not work. You should do reverse. Shift frame.setVisible (true); line at the end or at least after setting menu bar. You should always display frame after adding all components to it or else components added after displaying frame will not appear until repaint() is done.


From the comment by @sjr :

Sometimes revalidate is required (not only repaint) as altering a container (adding/removing/resizing components) after the container has been displayed.