Let’s say for example you have a list of items or a large grid of components, and you want to implement some sort of hover/rollover mechanism. The easy way to do this would simply be to add a MouseListener to every component and use the mouseEntered and mouseExited methods. Another way that you can do it is to determine the component based on the location of the mouse, for example you have a 2D array of JLabels and you determine which label is under the pointer by using something like:;
private void setRolloverIndices(Point p){
this.rolloverRow = p.y / this.labelHeight;
this.rolloverCol = p.x / this.labelWidth;
}
private JLabel getRolloverLabel(){
// assume safe values
return labels[rolloverRow][rolloverCol];
}
Is it worth bothering with pixel / grid calculation, or are listeners generally efficient enough to handle many components?
The same listener can be added to several components, and the component triggering the event is available using the event’s
getSource()orgetComponent()method. No need to guess based on the point location.