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

Chr*_*ler 7 java swing location selection jlist

如何通过JList点击位置从a获取组件?

我有自己的列表单元格渲染器,我插入一些面板和标签.现在我想得到例如用户点击的标签.

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

Mad*_*mer 18

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

  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);
Run Code Online (Sandbox Code Playgroud)