0

I have a JMenuBar that has one menu and three JRadioButtonMenuItems:

JMenuBar menuBar;
JMenu menu = new JMenu("Menu");
JRadioButtonMenuItem rbMenuItem;

I declare it:

    menu = new JMenu("A Menu");
   ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);

group.add(rbMenuItem);
menu.add(rbMenuItem);
menuBar.add(menu);

and I set it as the menu bar:

this.setJMenuBar(menuBar);

I run the file and it gives me:

Exception in thread "main" java.lang.NullPointerException
    at geometry.tools.main.RectangleFrame.<init>(RectangleFrame.java:47)
    at geometry.tools.main.RectangleFrame.main(RectangleFrame.java:95)
Java Result: 1

Line 47 is:

menuBar.add(menu);

and line 95 is:

 RectangleFrame thr = new RectangleFrame();

in the:

public static void main(String[] args){

    RectangleFrame thr = new RectangleFrame();
}

I don't really understand why. I haven't specified any value as null so I don't see why I get this error.

Thanks a lot.

DLJ
  • 333
  • 2
  • 6
  • 19

2 Answers2

2

menuBar is not initialized

JMenuBar menuBar = new JMenuBar();
sanbhat
  • 17,522
  • 6
  • 48
  • 64
  • @DLJ In java any un-initialized reference throws NPE, if tried to access it. its not specific to `JMenuBar` – sanbhat Jul 21 '13 at 16:47
0

You have to create an instance of your menubar.

JMenuBar menuBar = new JMenuBar()

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170