我想在使用 Swing 单击按钮时获取按钮对象的名称。我正在执行以下代码:
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) ;
}
}
在变量 s
中,我正在获取按钮的命令值,但我想获取按钮的名称,例如 b1
或 b2
。我怎样才能得到这个?
最佳答案
使用 ae.getSource()
方法来获取按钮对象本身。像这样的东西:
JButton myButton = (JButton)ae.getSource();
关于java - 如何在java中的点击事件中获取按钮名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13832513/