Macas
Macas

Reputation: 560

Java getName of obj that activated MouseListener

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

Answers (2)

Pete B.
Pete B.

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

Cedric Reichenbach
Cedric Reichenbach

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

Related Questions