How to get button name in click event in java

I want to get the name of the button object when I click the button with swing. I implement 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 s variable, I get the command value of the button, but I want to get the name of the button, for example, b1 or b2 how can I get this

+4
source share
4 answers

Use the ae.getSource() method to get the button object itself. Sort of:

 JButton myButton = (JButton)ae.getSource(); 
+6
source

You are asking about how to get the name of a variable, which you don’t need to get, because it is misleading and is actually not that important and almost does not exist in the compiled code. Instead, you should focus on getting references to objects, not variable names. If you need to associate an object with a string, then you need to use a Map, for example, HashMap<String, MyType> or HashMap<MyType, String> , depending on what you want to use as a key, but again do not put too much Dependence on variable names, since not finite variables can change links when the hat falls, and objects can refer to more than one variable.

For example, in the following code:

 JButton b1 = new JButton("My Button"); JButton b2 = b1; 

what variable name is the name? Both b1 and b2 belong to the same exact JButton object.

And here:

 JButton b1 = new JButton("My Button"); b1 = new JButton("My Button 2"); 

What is the variable name for the first JButton object? Does it matter that the variable b1 does not apply to this source object?

Again, do not put your faith in variable names, as they often mislead you.

+4
source

If you need a name, there is a function to get it:

getName

but you should also use setName.

+1
source

If you want to get buttons b1, b2, you can have ae.getSource () .

If you want button shortcut names to be used, ae.getName ()

+1
source

All Articles