dnawab
dnawab

Reputation: 123

mouseClicked event in a case where a JLabel is placed on top of another JLabel

I have a JLabel (say label1) on my JFrame at certain coordinates, then I have another JLabel (say label2) that is placed exactly on top of label1 (i.e. it has exactly the same origin and size as label1).

I have registered both these labels to receive mouseClicked event.

label1 = new JLabel();
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setName("label1");
label1.addMouseListener(this);
contentPane.add(label1);
label1.setBounds(0, 0, 40, 40);

label2 = new JLabel();
label2.setHorizontalAlignment(SwingConstants.CENTER);
label2.setName("label2");
label2.addMouseListener(this);
contentPane.add(label2);
label2.setBounds(0, 0, 40, 40);

But when I click on the label, only label1 gets notified (which was added before label2).

I am looking for a solution so that both my label objects get notified.

Any help would be highly appreciated.

Upvotes: 0

Views: 114

Answers (1)

camickr
camickr

Reputation: 324098

But when I click on the label, only label1 gets notified (which was added before label2).

Swing paints components in the reverse order that they were added to the panel. So label 2 gets painted before label 1. This explains why label 1 gets the event.

I am looking for a solution so that both my label objects get notified.

Add the MouseListner to the panel. Then you will need to loop through all the components on the panel to see if the component contains the mouse point. When you find a match you do your processing.

There is probably a better solution. Why do you need this? Why are you using a null layout.

Upvotes: 3

Related Questions