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.
Joined: Oct 13, 2005
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.
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.
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.