Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMenuBar not showing

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);
   }
}
like image 247
user1450466 Avatar asked Dec 15 '22 23:12

user1450466


1 Answers

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.

like image 122
Harry Joy Avatar answered Dec 30 '22 11:12

Harry Joy