So I have a mouse listener that is attached to multiple objects as so:
for (int i = 0; i < Grids.size(); i++) {
Grids.get(i).addMouseListener(new GameMouseListener());
}
Now the problem I have is I need to know which of the Objects activated the handler
obviously this wont work since the var “i” is not defined inside the class and was only used in the previous for loop.
how to I know using the Handler Which Specific Object has been clicked on.
public class GameMouseListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
if (Grid.get(i).isSelected()) {
Grid.get(i).unselected();
} else {
Grid.get(i).selected();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
You can use
e.getSource()to get the source of the event.Also, consider using
ActionListenerwhen possible (if the user might select with the keyboard).And one more thing – it the listener is generic, you might create only one instance of it instead of new instance for each component: