JMenu not showing until window resize

I am trying to create a sample program with a menu and some options. The problem is that when I run the program, the menu does not appear until the window is changed. I'm not sure what the problem is and I would appreciate any help.

Here is the code I am working with:

PS I have already imported all the libraries 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);

 }

 }

      

+3


source to share


1 answer


You are sizing and setting the JFrame visible to by adding a JMenuBar, so it should come as no surprise that the menu bar is not shown initially as it never appears initially. Your solution is to add JMenuBar wrapping before and render your GUI and solve your problem that way.



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);
   }
}

      

+2


source







All Articles