Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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..

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top