1

I have MenuButton, which extends AbstractButton. When I do setEnabled(true) within the class, there is no compiler error, but a runtime error of NullPointerException. (Note that the exact same code worked fine when it extended JButton). Relevant portions are below.

public class MenuItem extends AbstractButton{
    private String type = "";
    private String text = "";
    private int level;
public MenuItem(String place, String name, int height) {
        type = place;
        text = name;
        level = height;
        setEnabled(true); //This is where the error occurs.
    }
}

And the error:

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.AbstractButton.setEnabled(Unknown Source)
    at states.MenuItem.<init>(MenuItem.java:54)
    at states.MainMenu.<init>(MainMenu.java:26)
    at main.TheDarkSeaIslesPlatformer.main(TheDarkSeaIslesPlatformer.java:80)

This is not a duplicate because it has been initialized correctly. It also works when it extends JButton, so it is an issue with AbstractButton.

2 Answers2

3

You need to define a button model. This is the setEnabled method in AbstractButton.

/**
 * Enables (or disables) the button.
 * @param b  true to enable the button, otherwise false
 */
public void setEnabled(boolean b) {
    if (!b && model.isRollover()) {
        model.setRollover(false);
    }
    super.setEnabled(b);
    model.setEnabled(b);
}

Easiest way to do this is to set this in your constructor prior to setEnabled.

    setModel(new DefaultButtonModel());
Compass
  • 5,867
  • 4
  • 30
  • 42
2

You can't do that in the constructor. You should initialize your MenuItem where you need it and enable it

MenuItem menuItem = new MenuItem();
menuItem.setEnabled(true);
Ricardo
  • 9,136
  • 3
  • 29
  • 35