java JMenuBar不可见?为什么?

编程入门 行业动态 更新时间:2024-10-27 15:25:15
本文介绍了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不可见?为什么?

本文发布于:2023-11-15 05:05:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591395.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:java   JMenuBar

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!