有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing如何在java中单击事件时获取按钮名称

我想在使用Swing单击按钮时获得button对象的名称。我正在实现以下代码:

 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中,我得到按钮的命令值,但我想得到按钮的名称,比如b1b2。我怎么能得到这个


共 (3) 个答案

  1. # 1 楼答案

    如果你想得到按钮b1,b2,你可以有ae。getSource()

    如果您想知道可以使用的按钮的标签名称,ae。getName()

  2. # 2 楼答案

    如果需要名称,可以通过以下函数获取:

    getName

    但是你也必须使用setName

  3. # 3 楼答案

    使用^{}方法获取按钮对象本身。比如:

    JButton myButton = (JButton)ae.getSource();