views:

130

answers:

5

I've made a array full of JLabels and would like to add a listener to them.

The listener doesn't need to know exactly which one was clicked on, just that one was. Is there a way to add the listener to the whole array instead of using a 'for()' loop ?

Thanks for reading.

+1  A: 

Yyou can register the listener on the JPanel (or whatever component the buttons are in) so you only have to write a single listener.

extraneon
I don't think that jpanel supports ActionListeners..
Jack
+3  A: 

No there is no out of the box solution, AFAIK. Apart from using stupid hacks, I think you may have to use a for loop, and it may be a 10 line code, nothing to worry about.

Suraj Chandran
*.. Apart from using stupid hacks....* Or you can learn the library you're using and the options it offers: http://stackoverflow.com/questions/1693436/select-all-the-components-of-a-array-without-a-loop/1693675#1693675
OscarRyz
+2  A: 

You could wrap your array of JLabels in a class and implement your own Add() method which registers the listener upon adding them.

This way you wouldn't have to iterate over them afterwards..

andyp
A: 

If it was a list of JLabels, I'd suggest using CollectionUtils.forAllDo - method which allows you to apply same action to a bunch of objects.

valery_la99
+3  A: 

If your labels are added a to a container ( like a JPanel ) you can add a listener to this container and know which component is at certain location.

JPanel panel = new JPanel();
panel.addMouseListener( whichOneListener );
f.setContentPane( panel );

In this case I use a mouseListener because that give me the location where the user clicked.

private static MouseListener whichOneListener = new MouseAdapter() {
 public void mouseClicked( MouseEvent e ) {
  JComponent c = ( JComponent ) e.getSource();
  JLabel l  = ( JLabel ) c.getComponentAt( e.getPoint() );
  System.out.println( l.getText() );
 }

};

And prints correctly what component was clicked.

The full source code is here

OscarRyz