MouseInfo.getPointerInfo().getLocation()
gives the location of the mouse within the context of the screen.
JList#locationToIndex
expects the point to be within the context of the JList
.
This can be a little confusing at first, but, basically, when dealing with functionality like this, components except the point to be within their coordinate context, where 0x0 is the top, left corner of the component. This actually makes life a lot easier, as you don't constantly need to be translating between screen and component coordinates...
You will need to first convert the Point
to component coordinates...
SwingUtilities.convertPointFromScreen(p, list);
Then request the index of represented by the point
Also note that Swing is not thread safe, that means that you should only ever access or modify UI components from within the context of the Event Dispatching Thread.
So this makes...
String text = list.getModel().getElementAt(
list.locationToIndex(p));
lab.setText(text);
...very dangerous.
See Concurrency in Swing for more details
Without knowning exactly what you're trying to do it's difficult to provide alternative suggestions, but you might consider using a MouseListener
and/or MouseMotionListener
, registered to the JList
, instead
The immediate benefit of this is that the MouseEvent
is already converted to the coordinate space of the component that triggered the event