MouseListener on multiple JLabels not working as intended

I have 5 JLabels inside a JPanel which is inside a JFrame. I am adding the JLabels using a for loop which iterates through an array of Colors:

private JLabel target;

// This is the origin of the first label added.
Point origin = new Point(10, 20);

// This is the offset for computing the origin for the next label.
int offset = 200;

for (int i = 0; i < layerColors.length; i++) {
    target = createColoredLabel(layerColors[i], origin, targetIcon);
    layeredPane.add(target, new Integer(i));
    origin.x += offset;
}

// Create and set up a colored label with icon image.
private JLabel createColoredLabel(Color color, Point origin, ImageIcon icon) {
    JLabel label = new JLabel(icon);
    label.setVerticalAlignment(JLabel.TOP);
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setOpaque(true);
    label.setBackground(color);
    label.setBorder(BorderFactory.createLineBorder(Color.black));
    label.setBounds(origin.x, origin.y, 175, 263);
    label.addMouseListener(this);

    return label;
}

This creates 5 JLabels, with the same ImageIcon assigned to each, spread horizontally across the JPanel. Each one has a MouseListener added to it but only the last label to be added triggers the event.

@Override
public void mouseClicked(MouseEvent e) {
    if (e.getSource().equals(target)) {
        Toolkit.getDefaultToolkit().beep();
    }
}

I have a secondary issue involving a label containing an ImageIcon trailing my cursor which stops when I mouse over any of the 5 labels. I imagine it's a layer indexing issue but can't solve it.

Any help with these is much appreciated thanks!

1
задан hamena314 28 January 2016 в 10:35
поделиться