How can I fetch a component from a JList
, with the click location?
I have my own list cell renderer where I insert some panels and labels. Now i want to get e.g. the label where the user clicked at.
I tried the method list.getComponentAt(evt.getPoint());
but it returns only the entire JList
.
I've not tested this, but the basics would be...
JList#locationToIndex(Point)
to get the index of the element at
the given point.JList#getModel#getElementAt(int)
).ListCellRenderer
using JList#getCellRenderer
.Component
representationPoint
to the Component
s contextgetComponentAt
on the renderer...Possibly, something like...
int index = list.locationToIndex(p);
Object value = list.getModel().getElementAt(int);
Component comp = listCellRenderer.getListCellRendererComponent(list, value, index, true, true);
comp.setBounds(list.getCellBounds(index, index));
Point contextPoint = SwingUtilities.convertPoint(list, p, comp);
Component child = comp.getComponentAt(contextPoint);
MadProgrammer's works fine as long as the user doesn't click outside a cell. If he does that, the index returned by locationToIndex() will be the last index's cell, so the converted point will be "under" the rendered component
To check if the user really clicked a cell you have to do:
int index = list.locationToIndex(p);
if (index > -1 && list.getCellBounds(index, index).contains(p)){
// rest of MadProgrammer solution
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With