I’m having a problem with adding MouseListeners to a set number of Jlabels that are created inside a loop. The program I’m creating needs to change the icon of a JLabel when the user hovers over the label.
I’ve created a for loop to initialize a label that’s declared globally, set a border, add a mouse listener and add the label to a panel.
JLabel label;
for(int i = 0; i < 20; i++)
{
label = new JLabel();
label.setBorder(new LineBorder(Color.BLACK));
label.setMouseListener(this);
panel.add(label);
}
container.add(panel);
Then in my mouse listener I have
public void mouseEntered(MouseEvent e)
{
if(e.getSource().equals(label))
{
label.setIcon(image);
}
}
This seems to work fine, it adds 20 labels to the frame and adds the border but for some reason, the action listener is only being activated on the last label that is added. Can anyone tell me why this is happening or point me in the right direction please?
Any help is appreciated.
((JLabel)e.getSource()).setIcon(image);?