5

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);
   }
}
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
user1450466
  • 51
  • 1
  • 1
  • 2

2 Answers2

11

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.

Community
  • 1
  • 1
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • +1 This is probably right. Sometimes revalidate is required (not only repaint) as altering a container (adding/removing/resizing components) after the container has been displayed requires that you call `revalidate` on the container. – sjr Jun 12 '12 at 06:36
  • @sjr thank you so much you just saved my exam Thank you so much – user1450466 Jun 12 '12 at 13:20
3

Try this, it works.

Adding of components to the frame take place in its invisible state, and once all its components are set, then make it visible.

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 extends JFrame {
   public swing(){
      this.setSize(400,400);
      this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      this.setComponent();
   }

   public void setComponent(){
      JMenuBar bar = new JMenuBar();
      JMenu menu = new JMenu("Menu");
      this.setJMenuBar(bar);
      bar.add(menu);
   }

   public static void main (String[] args) {
      EventQueue.invokeLater(new Runnable(){
         public void run(){
            swing s = new swing();
            s.setVisible(true);
         }
      });
   }
}
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75