[英]When i run my code the menus appear vertical not horizontal how do i change this?
Screenshot of the error 错误的屏幕截图
import javax.swing.*;
public class Task1 {
public static void main (String[] args) {
Task1 a = new Task1();
}
public Task1() {
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(400,500);
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu help = new JMenu("help");
menuBar.add(help);
menuBar.add(file);
frame.add(menuBar);
JMenuItem load = new JMenuItem("Load");
JMenuItem save = new JMenuItem("Save");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem about = new JMenuItem ("About");
help.add(about);
file.add(exit);
file.add(save);
file.add(load);
}
}
This code for some reason when I run it the menus appear vertical not horizontal and I don't know why. 出于某种原因,运行该代码时,菜单显示为垂直而不是水平,我也不知道为什么。 I know this is a basic thing but I cant think of a solution that doesn't result in errors.
我知道这是基本的事情,但是我想不出不会导致错误的解决方案。
It's because you're using JFrame.add()
instead of JFrame.setMenuBar()
. 这是因为您使用的是
JFrame.add()
而不是JFrame.setMenuBar()
。 The former adds components (which JMenuBar
is) to the inner contentPane
of the JFrame
. 前者将组件(
JMenuBar
是)添加到JFrame
的内部contentPane
中。 Change your code from this: 从此更改代码:
frame.add(menuBar);
To this: 对此:
frame.setMenuBar(menuBar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.