This question already has an answer here:
这个问题在这里已有答案:
- Java Swing : why must resize frame, so that can show components have added 2 answers
Java Swing:为什么必须调整框架大小,以便显示组件添加了2个答案
I am new to java swing class and was learning how to add menubars and menus in JFrame.
我是java swing类的新手,正在学习如何在JFrame中添加菜单栏和菜单。
I have written a simple example but the JFrame
is displayed empty and I don't know why because I have included setJMenuBar()
method in my code then also menubar isn't visible.
我写了一个简单的例子,但JFrame显示为空,我不知道为什么因为我在我的代码中包含了setJMenuBar()方法,所以菜单栏也不可见。
Here is my code
这是我的代码
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();
}
}
And here is the output of this code.
以下是此代码的输出。
1 个解决方案
#1
2
Because you are using setVisible(true);
before you set this.setJMenuBar(menubar);
因为你正在使用setVisible(true);在设置this.setJMenuBar(menubar)之前;
so chnage the order and setVisible(true);
in the end.
所以chnage的顺序和setVisible(true);到底。
Your code should be like this:
你的代码应该是这样的:
....
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);
....
Hope this can help you.
希望这可以帮到你。
#1
2
Because you are using setVisible(true);
before you set this.setJMenuBar(menubar);
因为你正在使用setVisible(true);在设置this.setJMenuBar(menubar)之前;
so chnage the order and setVisible(true);
in the end.
所以chnage的顺序和setVisible(true);到底。
Your code should be like this:
你的代码应该是这样的:
....
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);
....
Hope this can help you.
希望这可以帮到你。