Question

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!

Was it helpful?

Solution

Your mouseClicked(MouseEvent evt) method only checks to see if the event source was a single component (target) which, as Geoffrey points out, is that last label you added. Try adding this as the first line in your mouseClicked method.

System.out.println("Color: " + ((JLabel)evt.getSource()).getBackground());

Note: Untested. Hopefully Color has a nice toString() implementation.
Note 2: You may get a ClassCastException if you added the class as a mouse listener to any other component.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top