简体   繁体   English

将JMenuBar添加到JFrame

[英]add JMenuBar to JFrame

i have this code , i want to add a jMenuBar1 to frame but in execution i have an empty window 我有此代码,我想向框架添加jMenuBar1,但在执行中我有一个空窗口

public hhh()  {
    // TODO Auto-generated constructor stub
    frame = new JFrame("A window");
    frame.setSize(500, 500);
    frame.setVisible(true);
    frame.setLayout(null);
    Container c=  frame.getContentPane();
    c.setLayout(null);
    jMenuBar1 = new JMenuBar();
    jMenuBar1.setBounds(10, 10, 100, 500);
    jMenuBar1.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
    jMenuBar1.setFont(new Font("Calibri", 1, 24)); 
    jMenu1.setText("File");
    jMenuBar1.add(jMenu1);
    jMenu2.setText("Edit");
    jMenuBar1.add(jMenu2);
    frame.setJMenuBar(jMenuBar1);
    c.add(jMenuBar1);  
        frame.pack();         
}

help me please 请帮帮我

You set the layout of the Container and the JFrame to null . 您将ContainerJFrame的布局设置为null As a consequence, no content can be displayed. 结果,无法显示任何内容。 Just don't do that and it should work. 只是不要这样做,它应该可以工作。 In fact, never set the layout to null . 实际上,切勿将布局设置为null

i want to add a jMenuBar1 to frame 我想将jMenuBar1添加到框架

frame.setJMenuBar(jMenuBar1);
//c.add(jMenuBar1);  // get rid of this

You add the menubar to the frame using the setJMenuBar(...) method which is correct. 您使用正确的setJMenuBar(...)方法将菜单栏添加到框架。

But then you also add the menu bar to the content pane, which is incorrect. 但是,然后您还将菜单栏添加到内容窗格中,这是不正确的。 Get rid of this statement. 摆脱这种说法。

A component can only have a single parent. 一个组件只能有一个单亲。 So the menu bar gets removed from the frame and gets added to the content pane. 因此,菜单栏将从框架中删除,并添加到内容窗格中。 But the content pane is using a null layout and the size of the menu bar is (0, 0) so there is nothing to display. 但是内容窗格使用的是null布局,并且菜单栏的大小为(0,0),因此没有任何显示。

So: 所以:

  1. add the menu bar to the frame using the setJMenuBar(..) method only. 仅使用setJMenuBar(..)方法将菜单栏添加到框架。
  2. add other components to the content pane of the frame, but the content pane should be using layout managers, not a null layout. 将其他组件添加到框架的内容窗格,但是内容窗格应使用布局管理器,而不是空布局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM