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?
Action
) to each button. Problem vanishes. Note thatb1
is not the 'name' of any button in that code. Neither of those buttons has a user defined name. 2) Only one of those buttons would be visible. 3) Please use a consistent and logical indent for code blocks. – Sorcha