Java 为什么Jmenubar不是';即使在添加setJMenubar()方法后,我的Jframe中也看不到它吗?

Java 为什么Jmenubar不是';即使在添加setJMenubar()方法后,我的Jframe中也看不到它吗?,java,swing,Java,Swing,我是JavaSwing类的新手,正在学习如何在JFrame中添加菜单栏和菜单 我写了一个简单的例子,但是JFrame显示为空,我不知道为什么,因为我在代码中包含了setJMenuBar()方法,所以菜单栏也不可见 这是我的密码 import java.awt.*; import javax.swing.*; import java.awt.event.*; public class jmenuexample extends JFrame //implements ActionListener {

我是JavaSwing类的新手,正在学习如何在JFrame中添加菜单栏和菜单

我写了一个简单的例子,但是
JFrame
显示为空,我不知道为什么,因为我在代码中包含了
setJMenuBar()
方法,所以菜单栏也不可见

这是我的密码

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class jmenuexample extends JFrame //implements ActionListener
{
    JLabel title;
    JMenuBar menubar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    jmenuexample()
    {
        setTitle("JMenu Example");
        setSize(750, 450);
        //setLayout(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        menubar = new JMenuBar();
        menu = new JMenu("File");
        menuItem = new JMenuItem("New\tCtrl+N");
        menu.add(menuItem);
        menuItem = new JMenuItem("Open\tCtrl+O");
        menu.add(menuItem);
        menuItem = new JMenuItem("Save\tCtrl+S");
        menu.add(menuItem);
        //menu.addSeparator();
        menuItem = new JMenuItem("Exit");
        menu.add(menuItem);
        menubar.add(menu);
        /*panel = new JPanel();
        panel.setLayout(new GridLayout());
        panel.setBounds(250,10, 400, 300);*/
        //add(menubar);
        //add(panel);
        this.setJMenuBar(menubar);
    }
    public static void main(String argv[])
    {
        new jmenuexample();
    }
}
这是这段代码的输出


因为您使用的是
setVisible(true)在设置之前
this.setJMenuBar(菜单栏)

因此,更改顺序并
setVisible(true)最后

您的代码应该如下所示:

....
menubar.add(menu);
/*panel = new JPanel();
 panel.setLayout(new GridLayout());
 panel.setBounds(250,10, 400, 300);*/
//add(menubar);
//add(panel);
this.setJMenuBar(menubar);
setVisible(true);
....
希望这能对您有所帮助。

不要在菜单项文本中添加“Ctrl\u O”。相反,您需要使用
JMenuItem
setAccelerator(…)
方法。有关更多信息和工作示例,请阅读上Swing教程的部分。本教程还将帮助您更好地构造类,以便在
事件调度线程(EDT)
上创建组件。为所有Swing基础知识保留教程链接。“我对JavaSwing不熟悉”,然后开始正确操作:了解JFrame(),不要从JFrame()继承。