0

I have a JRadioButtonMenuItem on my program that I can check in order to do some actions, so I need to get the state of this item (CHECKED or UNCHECKED).

So when i try to get the state with isSelected() method in the same class where the JRadioButtonMenuItem is declared, it works.

But when I try to get it in another class, thanks to a getter, I get the java.lang.NullPointerException.

Here is class where is my JRadioButtonMenuItem :

MainVue.java :

public class MainVue extends JFrame implements ActionListener {   
  private static  JRadioButtonMenuItem itemJour;

    this.itemJour = new JRadioButtonMenuItem("Jour");
    public static  JRadioButtonMenuItem getItemJour() {

    return itemJour;

 }
}

Then Here is the class where i want to GET the actual state of item.

ModeleListePush.java

public class ModeleListePush extends AbstractTableModel {
 private MainVue mv;
 private  boolean jour = false;
public ModeleListePush(Modele modele, Controleur controleur) {
    super();
    this.modele = modele;
    this.controleur = controleur;

    jour = MainVue.getItemJour().isSelected();
    System.out.println(jour);

    }
   }

When I execute the code I get this issue :

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at views.MainVue.getItemJour(MainVue.java:372)
at modele.ModeleListePush.<init>(ModeleListePush.java:30) 

Anyone has a idea ?

  • 2
    Why is itemJour declared as static? Why is getItemJour() declared as static? If it is indeed static, you should be calling it using MainVue.getItemJour() – FredK Aug 14 '15 at 15:26
  • I actually tried with MainVue.getItemJour() aswell but i get the same error. Thanks for your answer though @FredK – DeveloppeurDuTurfu Aug 14 '15 at 15:34

1 Answers1

2

well, you never actually instantiate the JRadioButton. This causes the Null Pointer Exception.

Also, perhaps a more memory efficient way of checking state would be to return a boolean derived from isSelected.

andrewdleach
  • 2,458
  • 2
  • 17
  • 25
  • 1
    Right. Make sure `itemJour` in your class `MainVue` actually gets set to the one that is being used by your application. It's likely the case that you _are_ initializing a `JRadioButtonMenuItem` elsewhere but you aren't actually assigning it to `itemJour` in the class. – Chris Sprague Aug 14 '15 at 15:15
  • Thanks for your answers guys but I'm not sure to get what you mean. If you had an exemple to share it would be really helpful since I'm pretty new to Java :) – DeveloppeurDuTurfu Aug 14 '15 at 15:31
  • 1
    @DeveloppeurDuTurfu if you never create a new instance of a JRadioButton, the default value of your reference will be null. You must write something like this: itemJour = new JRadioButton(); – andrewdleach Aug 14 '15 at 15:33
  • @andrewdleach Actually I did write it , I forgot to put this line in my question haha. So the problem come from somewhere else i guess – DeveloppeurDuTurfu Aug 17 '15 at 07:25