JMenuBar not showing
Asked Answered
H

2

6

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);
   }
}
Heraldic answered 12/6, 2012 at 6:18 Comment(0)
A
12

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.

Astrid answered 12/6, 2012 at 6:23 Comment(1)
+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.Greenhaw
F
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);
         }
      });
   }
}
Fanaticism answered 12/6, 2012 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.