简体   繁体   English

通过单击位置从JList获取组件

[英]Get a component from JList by click location

How can I fetch a component from a JList , with the click location? 如何通过单击位置从JList获取组件?

I have my own list cell renderer where I insert some panels and labels. 我有自己的列表单元格渲染器,我插入一些面板和标签。 Now i want to get eg the label where the user clicked at. 现在我想得到例如用户点击的标签。

I tried the method list.getComponentAt(evt.getPoint()); 我尝试了方法list.getComponentAt(evt.getPoint()); but it returns only the entire JList . 但它只返回整个JList

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. 使用JList#locationToIndex(Point)获取给定点的元素索引。
  2. Get the "element" at the specified index (using JList#getModel#getElementAt(int) ). 获取指定索引处的“元素”(使用JList#getModel#getElementAt(int) )。
  3. Get the ListCellRenderer using JList#getCellRenderer . 使用JList#getCellRenderer获取ListCellRenderer
  4. Render the element and get it's Component representation 渲染元素并获取它的Component表示
  5. Set the renderer's bounds to the required cell bounds 将渲染器的边界设置为所需的单元格边界
  6. Convert the original Point to the Component s context 将原始Point转换为Component的上下文
  7. Use getComponentAt on the renderer... 在渲染器上使用getComponentAt ...

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. 只要用户不在单元格外单击,MadProgrammer就可以正常工作。 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 如果他这样做,locationToIndex()返回的索引将是最后一个索引的单元格,因此转换后的点将位于渲染组件的“下”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM