aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Listeners on an array of checkboxes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Listeners on an array of checkboxes" Watch "Listeners on an array of checkboxes" New topic
Author

Listeners on an array of checkboxes

Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Quick question - I have a 16 x 16 array of checkboxes and a want to put a listener on each of them, and for the action to be dependent on which one is clicked.

I've implemented this by extending JCheckBox in an inner class and implementing ActionListener on that. By extending JCheckBox I can also add private variables so that the checkbox can identify its position in the array.

So I have a loop in the setup routine that goes through the combinations, and a line

and the inner class is

I just wanted to check if this is the proper way of doing this. In the examples I've seen, the object calling addActionListener hasn't been the same as the one in the argument, but here it seems necessary, or I can't think how to identify which checkbox has been clicked.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36513
    
  16
Why don't you create some sort of Listener class which takes the identity of the box as fields? I would add the Listeners at the same time as creating the boxes. Various old threads about Listeners: 1 (don't count the spellling errors), 2. There are others.That would work with a GridLayout for i rows and j columns.There are other sorts of Listener you can add to check boxes; look through the documentation to see what sorts.
Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Thanks for the suggestions.

What I've actually done is pretty much exactly the same as what you suggest, except using an extension of JCheckBox rather than a new class called xxxListener. On reflection there's no reason why I need to extend the JCheckBox and it would be better to just create a new BoxListener class. Knew it wasn't quite right, but couldn't quite work out how.

Thanks again.

Edit to say: it was the idea of passing constructor arguments to the ActionListener that I hadn't seen before, so I didn't think of it. Although I'd realised I needed them for my RCheckBox constructor. My version works fine, but I'll change it to the more orthodox way.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36513
    
  16
 
Don't get me started about those stupid light bulbs.
 
subject: Listeners on an array of checkboxes
 
Similar Threads
HFJ BeatBox program, problems
searching JFrame
JCheckBox problem
help with .isSelected
Check/Uncheck check boxes when All check box is enabled/disabled...