6

如何JList使用单击位置从 a 中获取组件?

我有自己的列表单元格渲染器,可以在其中插入一些面板和标签。现在我想获取例如用户点击的标签。

我尝试了该方法list.getComponentAt(evt.getPoint());,但它只返回整个JList.

4

2 回答 2

17

我没有测试过这个,但基础知识是......

  1. 用于JList#locationToIndex(Point)获取给定点的元素索引。
  2. 获取指定索引处的“元素”(使用 JList#getModel#getElementAt(int))。
  3. 获取ListCellRenderer使用JList#getCellRenderer.
  4. 渲染元素并获取它的Component表示
  5. 将渲染器的边界设置为所需的单元格边界
  6. 将原始转换PointComponents 上下文
  7. getComponentAt在渲染器上使用...

可能,诸如...

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);
于 2013-02-17T23:31:15.477 回答
2

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

要检查用户是否真的点击了一个单元格,你必须这样做:

int index = list.locationToIndex(p);
if (index > -1 && list.getCellBounds(index, index).contains(p)){
    // rest of MadProgrammer solution
    ...
}
于 2014-08-21T12:18:12.157 回答