1

Im stuck today with a java error on an eclipse 3.8 platform.

I try to generate a simple MenuBar on a JFrame. The JMenuBar contains the JMenu("Help") and the JMenu contains a JMenuItem("Quit"). The class extends a JFrame. With the function (this.)setJMenuBar(MenuBar); I try to set my MenuBar to my JFrame, which should work fine as long I just have one MenuBar.

GUI-class code:

import javax.swing.*;
import java.awt.*;

public class Taschenrechner extends JFrame{

//Instanzvariablen im Zusamenhang mit dem Menu
private JMenuBar MenuBar;
private JMenu MenuHelp;
private JMenuItem MenuHelpQuit;

public Taschenrechner() {
    super();

    //Flaeche festlegen
    this.setSize(300,300);

    //Menukomponenten definieren
    MenuHelp= new JMenu("Help");
    MenuHelpQuit=new JMenuItem("Quit");

    //Menukomponenten zusammensetzen
    MenuHelp.add(MenuHelpQuit);
    MenuBar.add(MenuHelp);
    this.setJMenuBar(MenuBar);
}
}

my main-class code (declare objekt and setVisible):

public class Taschenrechnerstart {

public static void main(String[] args) {
    Taschenrechner taschenrechner1 = new Taschenrechner();
    taschenrechner1.setVisible(true);
}
}

Now on starting the code I get a NullPointerException-error in the GUI-class on line:

MenuBar.add(MenuHelp);

and a NullPointerException-error in the main-class on the line:

Taschenrechner taschenrechner1 = new Taschenrechner();

Does someone have an idea why my code isn't working?

  • You didn't initialize `MenuBar`, it's set to `null` by default, so your code is actually `null.add(MenuHelp);`. – Maroun Jun 20 '15 at 10:54

1 Answers1

2
MenuBar.add(MenuHelp);

You are accessing the MenuBar variable without initializing it.

You are missing a

MenuBar = new JMenuBar (..);

BTW, your code would be more readable if you use Java naming conventions (variables should start with a lower case letter).

Eran
  • 387,369
  • 54
  • 702
  • 768