0

I asked a few hours ago (see: Java CheckboxMenuItem get/setState) how I can change the state from my CheckBoxMenuItem.

The user GhostCat correctly suggested to me that in order to change the state I have to tell the object's entries its values.

My Menu:

Menu notiSET = new Menu("Benachrichtigungen");
CheckboxMenuItem ns1 = new CheckboxMenuItem("On");
CheckboxMenuItem ns2 = new CheckboxMenuItem("Off");

I tried using notiSET.countItems() which gives me correctly 2 as an answer. Following that I used

System.out.println(notiSET.getItem(0));
System.out.println(notiSET.getItem(1));

to identify the entries.

Output:

java.awt.CheckboxMenuItem[chkmenuitem0,label=On,state=false]
java.awt.CheckboxMenuItem[chkmenuitem1,label=Off,state=false]

Now I am trying to change the value of state=false from chkmenuitem0.

I tried using notiSET.getItem(0).setState(boolean); but the method is not known.

enter image description here

What am I doing wrong? Thanks.

Community
  • 1
  • 1
piguy
  • 516
  • 3
  • 10
  • 30
  • didn't you forget to cast your notiSET.getItem(0) to CheckboxMenuItem ? cause getItem return a JMenuItem not a CheckboxMenuItem – Venom Mar 14 '17 at 14:31
  • @basslo I think what I wrote is correct - using `notiSET.getItem(0).setLabel("test");` changes the value from `On` to `test` – piguy Mar 14 '17 at 14:36
  • CheckboxMenuItem is a subclass of JMenuItem so it inherits the setLabel method from it that's why it works. But JMenuItem doesn't have setState(boolean ) method. – Venom Mar 14 '17 at 14:38
  • Look at the answer below. It is possible. You only have to cast your JMenuItem to CheckboxMenuItem. – Venom Mar 14 '17 at 14:42

1 Answers1

0

you should cast your JMenuItem returned by getItem into CheckboxMenuItem like that :

((CheckboxMenuItem)notiSET.getItem(0)).setState(boolean)
Venom
  • 1,010
  • 10
  • 20
  • This works great! Is this a legit workaround or tricking? Thanks for helping! – piguy Mar 14 '17 at 14:44
  • it is just casting! To cast you should be sure that the item is from the good type otherwise it will throw a exception. – Venom Mar 14 '17 at 14:45
  • @bassio Thank you for helping and giving an explanation. You helped me a lot. – piguy Mar 14 '17 at 14:46