JMenu 在 window 调整大小之前不会出现

JMenu not appearing until window is resized

我正在尝试创建一个示例程序,其中包含一个菜单和一些选项。 问题是当我 运行 程序时,菜单不会出现,直到 window 重新调整大小。我不确定问题出在哪里,如果有任何帮助,我将不胜感激。

这是我正在使用的代码:

P.S。我已经导入了我需要的所有库。

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

 }

 }

您在添加 JMenuBar 之前 设置大小并设置 JFrame 可见,因此菜单栏最初不显示也就不足为奇了,因为它最初从未呈现过。您的解决方案是添加 JMenuBar before 打包和可视化您的 GUI,这样您的问题就解决了。

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