【问题标题】:How to get the Class or Type of a button (JButton) in java from its Action Listener?java - 如何从其动作侦听器获取java中按钮(JButton)的类或类型?
【发布时间】:2014-04-25 08:50:31
【问题描述】:
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,一个是自定义的,第二个扩展了第一个。

java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=0,when=1395217216471,modifiers=Button1] on **Example1.MyCustomButton**[,165,0,55x55,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.synth.SynthBorder@8a13863,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: 我的目标是实现一个具有 2 类按钮的 gui,如果单击一个按钮,我有一组针对该类型按钮的操作,反之亦然,希望它能简化我的操作侦听器实现。

【问题讨论】:

  • 你应该考虑使用actions API,依赖类类型是错误的...
  • 无关:不要扩展任何 JSomething,它们是为按原样使用而设计的

标签: java swing awt paintcomponent


【解决方案1】:

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,这是一个带有配置信息的动作的自包含概念,那么你就不用关心了......

【讨论】:

    【解决方案2】:

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

    但是你为什么想要它?

    【讨论】:

      【解决方案3】:

      actionPerformed()中使用ActionEventgetSource()方法:

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

      【讨论】:

        【解决方案4】:

        试试下面的代码

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

        使其更健壮,代替

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

        优势:

        • 如果将来您更改 MyCustomButton 类的包,那么它也可以正常工作。
        • 在编译时捕获包中的更改

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-06-27
          • 1970-01-01
          • 1970-01-01
          • 2015-05-09
          • 2016-12-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-21
          相关资源
          最近更新 更多