2014-01-05 19 views
2

我在女巫中有一个Swing GUI,每个按钮都有自己的监听器。之后,我添加了另一个执行一组按钮的公共逻辑的侦听器:请求在执行选定操作之前保存表单数据。Swing - 管理同一个按钮上的多个监听器链条

我把它简单地:

myButton.addActionListener(commonListener); 
myButton.addActionListener(customListener); 

现在的问题是,当在共同侦听逻辑失败(或当用户将中止操作),我需要防止其他收听到被调用。我怎样才能做到这一点?

+0

修改你的逻辑:**错**依赖于监听器通知的顺序 – kleopatra

回答

3

我会建议一个像下面的东西来实现你的目标。

您可以拥有一个动作侦听器,并通过类层次结构继承常用的功能,而不是拥有两个动作侦听器。

你可以有一个父类如下

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public abstract class AbstractButtonActionListener 
           implements ActionListener { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if(commonActionPerformed(e)){ 
      customActionPerfroemd(e); 
     } 
    } 

    public abstract void customActionPerfromed(ActionEvent e); 


    /** 
    * 
    * @param e 
    * @return true if the custom aciton should be performed 
    */ 
    public boolean commonActionPerformed(ActionEvent e) { 
     //method implementation 
    } 

} 

commonActionPerformed方法将处理常用逻辑并返回true,如果流动应该继续。现在你可以添加一个动作监听器到按钮,如下所示

button.addActionListener(new AbstractButtonActionListener() { 

    @Override 
    public void customActionPerformed(ActionEvent e) { 
     //perform the custom logic here 
    } 
}); 
相关问题