Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a component from JList by click location

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.

like image 342
Christian 'fuzi' Orgler Avatar asked Feb 17 '13 23:02

Christian 'fuzi' Orgler


2 Answers

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);
like image 161
MadProgrammer Avatar answered Nov 10 '22 20:11

MadProgrammer


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
    ...
}
like image 45
dtortola Avatar answered Nov 10 '22 20:11

dtortola