Raees Khan
Raees Khan

Reputation: 369

In Java how to get name of component which is clicked

I want to know the name of the component which is clicked, for that I am doing something like this:

@Override
    public void mouseClicked(MouseEvent clicked) {
        if( clicked.getSource() instanceof JLabel )
            System.out.println( clicked.getComponent().getName() );
    }

but this is returning "null", please tell how can I get the component's name which is clicked?

Upvotes: 0

Views: 3170

Answers (2)

Hernanibus
Hernanibus

Reputation: 98

As

Reimeus

sais, names for components are not set automatically or implicitly as happens in other programming languajes, the name has to be set explicitly first.

You can do this by assigning a name for example upon construction using,

(again as said by Reimeus)

label.setName("MyLabel");

Other way is (if for example you are creating the form builder in a NetBeans Design mode) assign the name property in your favorite GUI constructor (Eclipse, NetBeans, IntelliJ...).

If you have done so, then when you program you listener you can get the object that generate the event using getSource() and cast it to your known control type, in this case a JLabel. Then you can use getName().

It would look something like this:

  public void mousePressed(java.awt.event.MouseEvent evt)
  {
    javax.swing.JLabel senderName = (javax.swing.JLabel) evt.getSource();
    switch(senderName.getName())
    {
      case "myLabel" : //DO what ever you want to do
      ...........
    }
  }

Hope it help you.

Upvotes: 1

Reimeus
Reimeus

Reputation: 159754

getName returns null by default so you need to set it explicitly:

label.setName("MyLabel");

Upvotes: 2

Related Questions