0

i have this code , i want to add a jMenuBar1 to frame but in execution i have an empty window

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

FRIDI Mourad
  • 87
  • 1
  • 6
  • 16
  • Is jMenu1 and jMenu2 ever initialized? – Jorel Ali May 26 '16 at 18:26
  • 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson May 26 '16 at 19:00

2 Answers2

1

You set the layout of the Container and the JFrame to 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.

Tobias Brösamle
  • 598
  • 5
  • 18
1

i want to add a jMenuBar1 to frame

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

You add the menubar to the frame using the setJMenuBar(...) method which is correct.

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.

So:

  1. add the menu bar to the frame using the setJMenuBar(..) method only.
  2. add other components to the content pane of the frame, but the content pane should be using layout managers, not a null layout.
camickr
  • 321,443
  • 19
  • 166
  • 288