Reputation: 369
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
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