Search code examples
javaswingjframejmenubar

JMenu not appearing until window is resized


I am trying to create a sample program that has a menu and some options on it. The problem is When i run the program, the menu does not appear until the window is re-sized. I am not sure what the problem is and I would appreciate any help.

Here is the code that I am working with:

P.S. I already imported all of the libraries that I need.

public class TextEditor {


public static void main(String[] args) {
     JFrame f = new JFrame();

    f.setSize(700,500);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(true);
    f.setVisible(true);

    JMenuBar menuBar = new JMenuBar();
    f.setJMenuBar(menuBar);

    JMenu file = new JMenu("File");

    menuBar.add(file);

    JMenuItem open = new JMenuItem("Open File"); 

    file.add(open);

 }

 }

Solution

  • You're setting sizes and setting the JFrame visible before adding your JMenuBar, so it's no wonder that the menu bar is not showing initially since it is never rendered initially. Your solution is to add the JMenuBar before packing and visualizing your GUI and in this way your problem is solved.

    import java.awt.Dimension;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    
    public class TextEditor {
    
       public static void main(String[] args) {
          JFrame f = new JFrame("Foo");
          f.add(Box.createRigidArea(new Dimension(700, 500)));
          JMenuBar menuBar = new JMenuBar();
          f.setJMenuBar(menuBar);
          JMenu file = new JMenu("File");
          file.setMnemonic(KeyEvent.VK_F);
          menuBar.add(file);
          JMenuItem open = new JMenuItem("Open File");
          file.add(open);
    
          f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          f.pack();
          f.setVisible(true);
       }
    }