有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当我运行我的代码时,菜单是垂直的而不是水平的。我该如何更改它?

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);


    }
}

由于某种原因,当我运行它时,菜单显示为垂直而不是水平,我不知道为什么。我知道这是一件基本的事情,但我想不出一个不会导致错误的解决方案


共 (1) 个答案

  1. # 1 楼答案

    这是因为您正在使用JFrame.add()而不是JFrame.setMenuBar()。前者将组件JMenuBar添加到JFrame的内部contentPane中。从以下位置更改代码:

    frame.add(menuBar);
    

    为此:

    frame.setMenuBar(menuBar);