NormR1
Posting Expert
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
From that other answerYou could use the ClientProperty associated with each JComponent to save any info about a component you want, like its position in an array. See the put... and get... methods.
Adding to that a bit: you can create a single listener instance that uses the getSource() method to get the label that was clicked, cast it to JLabel and get the value of that property. Add the listener to each label as you create it in your loop.
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
Create a small class to handle the click. Have a constructor for that class that takes an int as parameter and saves its value. Crate a new instance for each JLabel, with the JLabel's index as parameter. Now when you handle the event you have the index of the JLabel it relates to.
ps I also like Norm's client property approach
pps Forum protocol is that, if you cross-post in different sites, you should say so.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
I was also going to suggest something similar to what James mentioned above originally, but I like that the ClientProperty approach would allow for a single listener for all labels and the property is easier to change at run time if the array position were to change.
You could swap a custom listener object with a new one if necessary, but changing the client property seems easier and cleaner than digging out the listener and replacing it.
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
I think James' suggestion is probably closest to what I had in mind - though I will try all of your suggestions and I can hopefully get one of them to work !
I should point out that I just posted that for its conceptual simplicity assuming someone with a non-OO background. Personally I'm a long-time fan and user of client properties.
As a rule of thumb, if the logic is in with the GUI then you may probably want the array index, so that's fine. If you're doing the full MVC thing then you probably want the corresponding object in the model, for which a client property can give you the direct reference immediately.
JamesCherrill
Posting Genius
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073