【问题标题】:Adding a JMenuItem to a JMenu Causes Menu Bar to Disappear将 JMenuItem 添加到 JMenu 会导致菜单栏消失
【发布时间】:2019-09-15 19:29:00
【问题描述】:

当我尝试向菜单添加菜单项时,菜单栏消失。以下代码:

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class WedgeTextFrame  {  

    public static void main(String[] args){

         JFrame f = new JFrame("Menu");
         f.setVisible(true);
         f.setSize(400,400);
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

         JMenuBar menubar = new JMenuBar();

         JMenu file = new JMenu("File");
         JMenu tools = new JMenu("Tools");
         menubar.add(file);
         menubar.add(tools);

         f.setJMenuBar(menubar);
    }
}

结果

当我在 menubar.add(tools); 之后添加以下行时,定义并将 JMenuItem 添加到 JMenu

JMenuItem exit_item = new JMenuItem("Exit");
tools.add(exit_item);

菜单栏消失。我正在使用 JRE 1.8.0 运行 Eclipse 2019-06

【问题讨论】:

    标签: java swing jmenu jmenuitem


    【解决方案1】:

    这就是“所有 Swing 应用程序必须在它们自己的线程上运行”部分出现的地方。看看initial threadsthe Event Dispatch Thread。通过调用SwingUtilities#invokeLater 启动您的应用程序将解决您的问题。

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame("Menu");
            f.setVisible(true);
            f.setSize(400, 400);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JMenuBar menubar = new JMenuBar();
    
            JMenu file = new JMenu("File");
            JMenu tools = new JMenu("Tools");
            menubar.add(file);
            menubar.add(tools);
    
            JMenuItem exit_item = new JMenuItem("Exit");
            tools.add(exit_item);
    
            f.setJMenuBar(menubar);
        });
    }
    

    我也建议你在整个框架准备好后frame.setVisible(true)

    SwingUtilities.invokeLater(() -> {
        JFrame f = new JFrame("Menu");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        //add stuff to frame
    
        f.setSize(400, 400);
        f.setVisible(true); //Here at the end
    });
    

    【讨论】:

    • f.setVisible(true); //Here at the end f.setSize(400, 400); 应改为 f.pack(); // don't need to guess a size! f.setVisible(true); //Here at the end。 1) 设置大小应在设置可见框架之前完成。 2) 400 x 400 的大小并不比猜测好。调用 pack() 将使 GUI 尽可能大,以便显示它包含的组件。
    • @AndrewThompson 我没有包括整个pack(); 事情,因为我认为这是一个不同的故事。也许我错了...无论如何,一如既往,感谢您的补充,+1!
    • @SimonPeterkin 没问题。看看what should i do when someone answers my question
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    相关资源
    最近更新 更多