java - 如何在java中的点击事件中获取按钮名称

标签 java swing event-handling awt

我想在使用 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 中,我正在获取按钮的命令值,但我想获取按钮的名称,例如 b1b2。我怎样才能得到这个?

最佳答案

使用 ae.getSource()方法来获取按钮对象本身。像这样的东西:

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

关于java - 如何在java中的点击事件中获取按钮名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13832513/

相关文章:

python - Matplotlib 事件处理线选择器

java - Gradle 将缓存 8MB jar,但不会缓存 32MB jar

java - 使用 Joda,如何确定给定日期是否介于时间 x 和比 x 早 3 小时的时间之间?

java - 将 Java 函数传递给 KFunction

java - 如何根据输入的文本向JtextPane添加规则

javascript - jQuery/JavaScript : Event handlers only assigned during the last iteration of a loop

java - 尝试创建一个构造函数,该构造函数将使用参数中给出的数字初始化 'number' 并设置长度

java - 如何将值传递给菜单项单击时的旋转方法?

Java GUI 空白和空指针异常

C# 处理事件