Reputation: 560
I have a problem with my project. My problem is that I don't know how to get name of the label which has been activated by the MouseListener?
MouseListener works, and now I just need to get the name of the label which was activated by the mouselistener.
example
label1 = new JLabel("FirstLabel");
label1.addMouseListener(ml);
add(label1);
label2 = new JLabel("SecondLabel");
label2.addMouseListener(ml);
add(label2);
MouseListener ml = new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
otherLabel = // code to get labelname ( label1 or label2)
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
};
Upvotes: 3
Views: 607
Reputation: 3276
Read the java docs:
public Component getComponent()
Returns the originator of the event.
Returns:
the Component object that originated the event, or null if the object is not a Component.
Upvotes: 2
Reputation: 9319
Is that what you're looking for (not tested)?
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
String name = label.getText();
}
Sources:
Upvotes: 4