MouseListeners only being detected on last JLabel created in a loop

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.

Answers


((JLabel)e.getSource()).setIcon(image); ?


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?


Need Your Help

Can't configure locale in Docker image

ubuntu docker locale ubuntu-14.04 dockerfile

I'm trying to install a locale file in my Docker image, but for some reason it doesn't install correctly.

Emailing php output

php forms email output-buffering

I have built a jquery mobile form that submits to a php file. I want the following php output to also have the option of emailing it to the user.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.