简体   繁体   English

当我运行代码时,菜单显示为垂直而不是水平,该如何更改?

[英]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.

相关问题 如何在 java 中将我的 output 从水平更改为垂直? - how do i change my output from horizontal to vertical in java? 如何让我的 label 和组合框在 java 中显示为垂直而不是水平? 我尝试将布局设置为 null 但它隐藏了 label - How do I get my label and combo box to appear vertical instead of horizontal in java? I tried setting the layout to null but it hides the label 如何在我的JTextArea(java)中添加水平和垂直滚动条 - how do I add a horizontal and vertical scroll bar to my JTextArea (java) 如何将垂直列表输出到水平列表中 - How do I output the vertical list into horizontal lists 如何将垂直和水平滚动条置于JScrollPane中心? - How do I center the vertical and horizontal scrollbars in a JScrollPane? 如何为我的软件制作上下文菜单? - How do I make context menus for my software? 将卡片添加到JFrame时,如何使其卡片(JComponent)完全显示在JPanel中? - How do I get my Card (JComponent) to appear fully in my JPanel when I add it to my JFrame? 我正在尝试在我的 gui 中放置一个 imageicon,但是当我运行代码时它没有出现。 有人可以告诉我如何解决它 - I am trying to put an imageicon in my gui but it doesn't appear when I run the code. Can somebody tell me how to fix it 为什么在运行此JFrame时我的按钮不出现? - Why won't my buttons appear when I run this JFrame? 方向改变时如何将垂直滚动更改为水平滚动? - how to change scroll vertical to horizontal when orientation change?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM