如何从Action Listener中获取java中的按钮(JButton)的类或类型?

如何从Action Listener中获取java中的按钮(JButton)的类或类型?

问题描述:

private class MyCustomButton extends JButton{...} 
private class MyCustomButton2 extends MyCustomButton{...} 

public class Example1 extends JPanel{ 
    Example1{ 
    MyCustomButton b1=new MyCustomButton("0"); 
    MyCustomButton2 b2=new MyCustomButton1("b2"); 
    } 
    private class ButtonListener implements ActionListener//, KeyListener 
    { 
    public void actionPerformed(ActionEvent e) 
    { 
     System.out.println(e); 
    } 
} 

在上面的例子中,我有2个JButton,一个是自定义的,第二个扩展了第一个。如何从Action Listener中获取java中的按钮(JButton)的类或类型?

java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=0,when=1395217216471,modifiers=Button1] on **Example1.MyCustomButton**[,165,0,55x55,alignmentX=0.0,alignmentY=0.5,[email protected],flags=16777504,maximumSize=,minimumSize=,preferredSize=,defaultIcon=pressed.png,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=0,defaultCapable=true] 

为了实现我的动作监听器,我从打印输出java知道能够返回按下的按钮类,我该怎么做?

编辑1: 我的目标是实现一个gui,它有2个类的按钮,如果点击了一个按钮,我有一组操作,反之亦然,希望它会简化我的动作侦听器实现。

+1

被捉住你应该考虑使用的[动作API(http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) ,依靠类的类型是错误的... – MadProgrammer

+0

不相关:不扩展任何JSomething,它们被设计为使用原样 – kleopatra

ActionEvent提供了触发事件的source的引用,在你情况下,这将JButton

你可以简单地检查哪个按钮由源与已知的基准进行比较触发事件,但它会更简单,以利用按钮actionCommand属性...

if ("name of action".equals(source.getActionCommand())) {... 

这假定您设置的按钮actionCommand财产。

如果做不到这一点,你在下面的文本......

JButton btn = (JButton)e.getSource(); 
if ("0".equals(btn.getText()) {... 

就个人而言,这只是自寻烦恼,因为你可能有多个名称相同的按钮。最好使用按钮actionCommand属性。

一个更好的解决办法是只使用actions API,这是携带与它的配置信息,然后你不在乎的动作的自给自足的概念...

e.getSource().getClass().getName()返回按钮类的全名。

但是你为什么要这样做?

使用actionPerformed()ActionEventgetSource()方法:

if(e.getSource() instanceof MyCustomButton){ 

} else if(e.getSource() instanceof MyCustomButton1){ 

} else { 

} 

试试下面的代码

if(e.getSource().getClass()==MyCustomButton.class) 

,使其代替

if(e.getSource().getClass().getName.equals("com.x.y.z.MyCustomButton")) 

性能更加强大:

  • 如果将来您更改了类MyCustomButton的包,那么它也会正常工作。在包
  • 变化在编译时