【发布时间】:2012-11-29 17:30:24
【问题描述】:
我想在使用 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。我怎样才能得到这个?
【问题讨论】:
-
你想得到按钮的引用还是标签?
-
我想获取按钮的名称而不是按钮的标签
-
你的“名字”是什么意思?在您的示例中,名称是什么?
-
1) 为每个按钮添加一个单独的侦听器(或
Action)。问题消失。请注意,b1不是该代码中任何按钮的“名称”。这些按钮都没有用户定义的名称。 2) 只有其中一个按钮可见。 3) 请对代码块使用一致且符合逻辑的缩进。
标签: java swing event-handling awt