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?
Use the ae.getSource() method to get the button object itself. Something like:
JButton myButton = (JButton)ae.getSource();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With