java 将菜单栏添加到 JFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29061969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:36:46  来源:igfitidea点击:

Adding Menubar to JFrame

javajframemenubarjmenu

提问by zey

I have the following source code and i just dont get why my menubar/menu wont show on the JFrame, im somewhat new to programming

我有以下源代码,我只是不明白为什么我的菜单栏/菜单不会显示在 JFrame 上,我对编程有点陌生

public class drawingApp {
    public static void main(String[] args) {

        JFrame frame = new JFrame("DrawingApp");
        frame.setSize(600,800);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

        JMenuBar mb = new JMenuBar();
        JMenu menu1 = new JMenu("Colour");
        mb.add(menu1);
        JMenu menu2 = new JMenu("Size");
        mb.add(menu2);

        frame.setJMenuBar(mb);

    }
}

回答by Roan

I am not 100 % sure why the JMenu's don't show up but it's probably because there are no items in the JMenu's and therefore they are not rendered.

我不是 100% 确定为什么JMenu's 没有出现,但这可能是因为JMenu's中没有项目,因此它们没有被渲染。

So this is what was going wrong you created the JMenuBarthe Menu's but not the JMenuItems. This is how you create a JMenuBar:

所以这就是你创建JMenuBarMenu's 而不是JMenuItems. 这是您创建一个的方式JMenuBar

JFrame myframe = new JFrame();
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("size");
JMenuItem size = new JMenuItem("size");
menu.add(size);
menubar.add(menu);
myframe.setJMenuBar(menubar);

I hope this helps :)

我希望这有帮助 :)

回答by Paul

You add the menubar after your frame has been set visible. Due to this, the frame is first rendered and afterwards the menubar is added. Try:

在您的框架设置为可见后添加菜单栏。因此,首先渲染框架,然后添加菜单栏。尝试:

frame.setJMenubar(mb);
frame.validate();
frame.repaint();

this should solve the problem.

这应该可以解决问题。