【问题标题】:Own ActionListener with anonymous implementation? (busy cursor)拥有匿名实现的 ActionListener? (忙光标)
【发布时间】:2013-02-28 11:19:09
【问题描述】:

ActionListeners(带有匿名实现)通常添加如下:

someobject.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
        ...
    }
});

但我想在每个“actionPerformed”事件之前和之后执行我自己的代码。因此,假设我在自己的类中实现 ActionListener 接口,例如:

public class MyOwnActionListener implements ActionListener{
    public void actionPerformed(final ActionEvent ae) {
        // own code
            super.actionPerformed(ae); // I know, this makes no sense, cause ActionListener is an interface
        // own code
    }
}

我希望能够做类似的事情:

someobject.addActionListener(new MyOwnActionListener(){
    public void actionPerformed(ActionEvent ae){
        ...
    }
});

在我的课堂上,匿名actionPerformed 中的代码应该被执行而不是super.actionPerformed(ae);。我知道,我不能为 MyOwnActionListener 提供匿名实现,因为它是一个类而不是一个接口,并且 super.actionPerformed(ae); 不起作用,因为我想调用继承类的方法,而不是超类-但是我如何重新设计我的代码以尽可能少地更改 ActionListener 的匿名实现?

背景: 我正在尝试在一个非常庞大的 java 项目(有很多匿名 ActionListeners)上实现忙碌光标管理。所以,如果我必须将我自己的代码(更改光标)添加到每个匿名 actionPerformed() 我会发疯的。

有什么想法或建议吗?

【问题讨论】:

    标签: java swing cursor actionlistener anonymous-class


    【解决方案1】:

    试试;

    public abstract class MyOwnActionListener implements ActionListener{
        @Override
        public void actionPerformed(final ActionEvent ae) {
            // own code
            doActionPerformed(ae); 
            // own code
        }
    
        protected abstract void doActionPerformed(ActionEvent ae);
    }
    

    然后在子类中实现doActionPerformed。

    【讨论】:

    • 简单优雅 - 谢谢!
    【解决方案2】:

    如果您使用游标,请将其放入 finally。否则,如果出现问题,您将被卡在沙漏上。

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            doBefore(e);
            delegate.actionPerformed(e);
        }finally {
            doAfter(e);
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      你可以实现一个包装器 Action/Listener

      public WrapperAction extends AbstractAction {
      
          private Action delegate;
      
          public WrapperAction(Action delegate) {
             this.delegate = delegate;
          }
      
          @Override
          public void actionPerformed(ActionEvent e) {
              doBefore(e)
              delegate.actionPerformed(e);
              doAfter(e);
          }
      
          protected void doBefore(ActionEvent e) {
            ...
          }
      
          protected void doAfter(ActionEvent e) {
            ...
          }
      }
      

      注意:对于不完整的操作,它必须将其值(如启用、名称...)报告为委托的值,并监听委托属性的变化并根据需要通知其监听器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-04
        • 1970-01-01
        • 2017-08-23
        • 1970-01-01
        • 1970-01-01
        • 2012-07-04
        • 2018-09-04
        • 1970-01-01
        相关资源
        最近更新 更多