user2798694
user2798694

Reputation: 1033

How can I get a jButton from its name?

If i know just the name of a jButton, how can I get the button itself so I can set actionlistener and other stuffs?

I have a string which is the name of a jButton and i want to perform actions on the jbutton with that name if it exists?

Upvotes: 1

Views: 629

Answers (2)

Sage
Sage

Reputation: 15418

I have a string which is the name of a jButton and i want to perform actions on the jbutton with that name if it exists?

Your question is complete confusing, but to set name of a JButton or any other component we use component.setName(String name) function and to get the name of the component we use component.getName() function. Where component is any instance of JComponent. JButton is also a JComponent.

This is not preferable to me to rely on event.getActionCommand() to detect a source component of an event, rather try to make use of event.getSource() instead.

Upvotes: 1

Arun
Arun

Reputation: 105

If i am right you want to get the name given to jbutton ie.,close or login etc.,I have retrieved the name of the text using getText()

Then try this

   JButton jb=new JButton();
     String name=jb.getText();
     public void actionPerformed(ActionEvent ev){
    if(ev.getActionCommand().equals(name){
      //This is the action of jButton.   
    } 
 }

Upvotes: 1

Related Questions