java JMenuBar不可见?为什么? [英] java JMenuBar not visible? Why?

查看:208
本文介绍了java JMenuBar不可见?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚为什么菜单栏不可见.我有以下代码:

I cannot figure out why my menu bar isn't visible. I have following code:

//主

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Menu extends JFrame{
    public static void main(String[] args){

        JFrame frame = new JFrame();
        frame.setSize(500,350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        menuBar mbObj = new menuBar();

        mbObj.menuBar(frame);
    }
}

//菜单栏类

public class menuBar{

        private JMenu file,edit;
        private JMenuItem nFile ,oFile,sFile,saFile,exit;
        private JMenuItem undo,copy,paste;
        private JMenuBar bar;

        public void menuBar(JFrame frame){
            bar = new JMenuBar();
            frame.setJMenuBar(bar);
            bar.setVisible(true);
            file = new JMenu("File");
            edit = new JMenu("Edit");
            bar.add(file);
            bar.add(edit);
        }    
 }

推荐答案

在顶级窗口(这里是JFrame)上调用setVisible(true),仅在之后添加所有组件,包括JMenuBar .您还希望避免在任何情况下调用setSize(...),而是在添加所有组件之后且在调用setVisible(true)之前,使用布局管理器并在JFrame上调用pack().

Call setVisible(true) on the top-level window, here a JFrame, only after adding all components, including the JMenuBar. You will also want to avoid calling setSize(...) on anything, and instead use layout managers and call pack() on the JFrame after adding all components and before calling setVisible(true).

因此顺序应为:

// create JFrame
JFrame frame = new JFrame("Foo");

// here add all components to the JFrame
// .....
// done adding components

frame.pack();
// frame.setLocationRelativeToPlatform(true); // if you wish
frame.setVisible(true);

顺便说一句,类的名称应以大写字母开头,并且不具有与该类名称完全相同的方法,因为这会创建伪"构造函数,并使所有人感到困惑.

As an aside class names should begin with an upper case letter, and dont have methods with the exact same name as the class, as that creates a "pseudo"-constructor and will confuse everyone.

这篇关于java JMenuBar不可见?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆