【问题标题】:Java Menu Bar not appearing in Swing GUI despite setting to frame尽管设置为框架,但 Java 菜单栏未出现在 Swing GUI 中
【发布时间】:2017-12-23 17:22:04
【问题描述】:

我正在编写一个基本程序来练习和学习使用摆动 GUI,我已经构建了一个带有基本菜单的框架,将其添加到框架中,但是由于某种原因,当我运行该程序时它没有出现在框架。

public class GUITest {

private static int windowWidth = 500;
private static int windowHeight = 500;

private static JFrame frame;
private static JMenuBar menuBar;

public static void main(String[] args){
    build();
}

private static void build(){
    windowGen();
    menuGen();
}

private static void windowGen(){
    JFrame frame = new JFrame();
    frame.setLayout(null);
    frame.setSize(windowWidth,windowHeight);
    frame.setVisible(true);
}

private static void menuGen(){
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu("File");
    JMenuItem menuFileExit = new JMenuItem("Exit");
    menuFile.add(menuFileExit);

    menuBar.add(menuFile);

    frame.setJMenuBar(menuBar);
}   
}

你们中有人知道为什么会这样吗?

【问题讨论】:

  • 在显示框架之前添加它
  • 对,setVisible(true) 必须是您调用的最后一件事,因为那是所有组件都布置好的时候。如果需要修改菜单栏,那就有点不一样了。
  • 啊啊啊谢谢你=]

标签: java swing user-interface menu frame


【解决方案1】:

参考上面声明的它的静态变量,但是不要新建一个,这是第一个错误,另一个是没有为你的JFrame定义一个Layout

public class GUITest {

private static int windowWidth = 500;
private static int windowHeight = 500;

private static JFrame frame;
private static JMenuBar menuBar;

public static void main(String[] args){
    build();
}

private static void build(){
    windowGen();
    menuGen();
}

private static void windowGen(){
    frame = new JFrame();
    frame.setLayout(null);
    frame.setSize(windowWidth,windowHeight);
    frame.setVisible(true);
}

private static void menuGen(){
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu("File");
    JMenuItem menuFileExit = new JMenuItem("Exit");
    menuFile.add(menuFileExit);

    menuBar.add(menuFile);

    frame.setJMenuBar(menuBar);
}   
}

【讨论】:

  • 那么我要删除顶部的静态变量吗?还是像上面一样简单地删除单词 JFrame?我故意不分配布局,因为我对布局的经验很少,想自学如何在没有布局的情况下使用
  • 对于这个例子来说,删除之前的 JFrame 类就足够了,因为如果它没有创建新变量
  • 我刚刚尝试了这两种方法都没有结果:1)如您所展示的那样删除单词 JFrame(与菜单栏相同)2)在顶部初始化它们而不是没有结果,也许我理解您的评论错误的?让我感兴趣的是,我的窗口仍然出现,只是菜单没有出现?
  • 我用完整的代码回答了我的答案,验证并评论,更新页面
  • 对不起,我是这个网站的新手,我只能看到那个方法的代码,这是你的意思吗?因为我尝试过没有成功,抱歉,我确定我的 n00bness 令人沮丧
猜你喜欢
  • 1970-01-01
  • 2013-09-30
  • 2012-04-18
  • 2014-05-01
  • 2011-06-09
  • 2016-03-15
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
相关资源
最近更新 更多