Get a component from JList by click location
Asked Answered
A

2

7

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.

Acquah answered 17/2, 2013 at 23:18 Comment(2)
For a JList, add a ListSelectionListener. For better help sooner, post an SSCCE.Larisa
The JList does not container any components. It uses the ListCellRenderer to paint a "rubber stamp" of the component onto the list. That is, each element in the list is rendered using the same/single ListCellRendererOxytetracycline
O
17

I've not tested this, but the basics would be...

  1. Use JList#locationToIndex(Point) to get the index of the element at the given point.
  2. Get the "element" at the specified index (using JList#getModel#getElementAt(int)).
  3. Get the ListCellRenderer using JList#getCellRenderer.
  4. Render the element and get it's Component representation
  5. Set the renderer's bounds to the required cell bounds
  6. Convert the original Point to the Components context
  7. Use getComponentAt 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);
Oxytetracycline answered 17/2, 2013 at 23:31 Comment(0)
C
2

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
    ...
}
Containment answered 21/8, 2014 at 12:18 Comment(1)
This solved the problem I had where whenever I clicked below the list items, it would always get the last component.Jeromejeromy

© 2022 - 2024 — McMap. All rights reserved.