Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get button name on click event in java

I want to get the name of the button object on clicking the button using Swing. I am implementing the following code:

 class  test extends JFrame implements ActionListener
  {
   JButton b1,b2;
   test()
   {
    Container cp=this.getContentPane();
    b1= new JButton("ok");
    b2= new JButton("hi");
    cp.add(b1);cp.add(b2);
    b1.addActionListener(this);
    b2.addActionListener(this);
   }
public void actionPerformed(ActionEvent ae)
 {
 String s=ae.getActionCommand();
 System.out.println("s is"+s)       ;
} 
}

In the variable s I am getting the command value of the button but I want to get the name of the button, like b1 or b2. How can I get this?

like image 490
Adesh singh Avatar asked Dec 12 '12 03:12

Adesh singh


1 Answers

Use the ae.getSource() method to get the button object itself. Something like:

JButton myButton = (JButton)ae.getSource();
like image 149
Richard JP Le Guen Avatar answered Oct 25 '22 20:10

Richard JP Le Guen