Reputation: 45
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.
Upvotes: 2
Views: 252
Reputation: 1413
See my inline comments for explanation:-
JLabel label;
for(int i = 0; i < 20; i++)
{
label = new JLabel(); // variable re-assignment!
label.setBorder(new LineBorder(Color.BLACK));
label.setMouseListener(this);
panel.add(label);
}
// after executing the loop 20 times,
// 1) 'label' will hold the 20th instance of the JLabel due to variable re-assignment in loop
// 2) 'panel' will have 20 different instances of JLabel
container.add(panel);
now to solve your problem, you should have 20 different mouse listener instances and each mouse listener should have its own JLabel.
Upvotes: 0
Reputation: 285415
You only have one JLabel being referenced to by the label variable, the last one used, and so the if block will test of the source is the last JLabel. In other words your code is only doing what you're telling it to do. What are you trying to accomplish with that if block?
Upvotes: 5