• Post Reply Bookmark Topic Watch Topic
  • New Topic

Issue with JCheckbox  RSS feed

 
shalaka wadekar
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

My application has 2 JCheckboxes ch1 & ch2.

My requirement is that when I check 'ch1', action1 should be performed & when I check 'ch2', action2 should be performed.
Now I have written the following code for the itemStateChanged(ItemEvent e) method:

When I run my application & check 'ch1' Action1 is performed as expected .
Now the issue is that when I check 'ch2' (keeping 'ch1' checked), the entire method will be executed resulting in Action1 to be performed twice, which is undesirable.
I want both my checkboxes to be checked & both the Action methods to be executed only once.
Can anyone please suggest a way of doing this.

Please help..
Thanks in advance,
Shalaka
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even at a 1-second look I can see problems.

Having a single method, particularly if you are checking for which box is selected, looks like poor design.

You can add a ChangeListener or an ActionListener object to each of the check boxes. That can be a public class, a private class, or anonymous classes. I wrote about Listeners recently, here.
You can of course refer from one box to another in their methods. Just remember that a local variable referred to from an anonymous class has to be declared final.

Your ChangeListener can listen for the change when the box is selected, and also unselected. You would have to check whether an ActionListener does the same. You can also use an ActionListener on another Component, eg a JButton, which refers to your two boxes.

See how you get on with that lot, then tell us what happens.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!