尽管设置为框架,但Java菜单栏不会出现在Swing GUI中

问题描述 投票:-1回答:1

我正在编写一个基本程序,以便使用swing 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);
}   
}

你们中的任何人都知道为什么会这样吗?

java swing user-interface menu frame
1个回答
0
投票

引用上面声明的静态变量,但不创建新的,它是第一个错误,另一个不是为你的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);
}   
}
© www.soinside.com 2019 - 2024. All rights reserved.