I am new to Java Swing. I have a JList which displays a list of
JLabels. The JLabels each contain text and an image icon. Is there a
way to detect when a user clicks on the image icon vs. the text of the
JLabel?
Thanks
> I am new to Java Swing. I have a JList which displays a list of
> JLabels. The JLabels each contain text and an image icon. Is there a
> way to detect when a user clicks on the image icon vs. the text of the
> JLabel?
A JList cannot really display a list of JLabels. Rather, it displays its
cells using a ListCellRenderer, and that renderer can use a JLabel as the
renderer component.
Since there are really no JLabels in the UI, the JLabel cannot receive
mouse clicks - those go to the JList itself. So if you want to determine
whether the mouse click is "on" the icon, you will have to know where the
icon is painted. Obviously, in order to get that information, you want to
ask the object that decides where the icon will be painted. But as far as
I know, JLabel does not expose that information.
You may be able to get that information using a JLabel subclass, but I
suspect that will not be easy. You could also create your own component
using multiple JLabels that does expose it. Finally, you could just make
some assumptions about how a JLabel paints itself. Doing that is never
pretty, but sometimes it makes sense if you can write code that works, and
spend a lot less time writing it.
Although not documented, JLabel uses SwingUtilities.layoutCompoundLabel()
to decide where to place the text and the icon. If you use this approach,
I would definitely recommend that you make sure you isolate the code that
makes this assumption, by creating your own renderer class that provides a
method to get the icon position.

Signature
Regards,
John McGrath