[英]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... 我没有测试过这个,但基础知识是......
JList#locationToIndex(Point)
to get the index of the element at the given point. JList#locationToIndex(Point)
获取给定点的元素索引。 JList#getModel#getElementAt(int)
). JList#getModel#getElementAt(int)
)。 ListCellRenderer
using JList#getCellRenderer
. JList#getCellRenderer
获取ListCellRenderer
。 Component
representation Component
表示 Point
to the Component
s context Point
转换为Component
的上下文 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.