Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JLabel click event

Tags:

java

swing

If you have two JLabels in a JFrame both with the same MouseListener click event added to them, how can you tell which JLabel was clicked without creating a second actionlistener?

Note: both labels have the same text written on them so that cannot be used to tell them apart.

like image 605
jjj Avatar asked Mar 06 '26 16:03

jjj


2 Answers

This will get you a reference to the component ...

public void mousePressed(MouseEvent e) 
{
JComponent reference = e.getComponent();
}

For a more complete description look at the Swing Tutorial on MouseListeners

like image 121
Romain Hippeau Avatar answered Mar 08 '26 04:03

Romain Hippeau


Just make the two JLabels fields and then check the source of the MouseEvent:

if (e.getSource() == firstLabel) {
  ...
} else if (e.getSource() == secondLabel) {
  ...
}
like image 33
ColinD Avatar answered Mar 08 '26 04:03

ColinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!