如何暂时禁用Swing中的事件侦听器? [英] How to temporarily disable event listeners in Swing?

查看:136
本文介绍了如何暂时禁用Swing中的事件侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有模型和视图的Swing应用程序。在视图(GUI)中,有很多组件,每个组件都映射到模型对象的某些属性并显示其值。



现在有一些UI组件当用户界面中的值发生变化时,会自动触发某些模型属性的更新。这需要我在UI中重新加载完整的模型。这样我就进入一个无限更新循环,因为UI中的每个模型重新加载触发另一个模型重新加载。



我有一个标志指示加载过程, d喜欢临时抑制侦听器通知,而从模型中设置UI字段。所以我的问题是:



有没有办法在Swing中全局暂时禁用某些组件的侦听器,而不必删除并重新附加它们?

解决方案

您可以为侦听器使用一个常用的基类,并在其中使用静态方法来打开或关闭侦听器:

  public abstract class BaseMouseListener实现ActionListener {

private static boolean active = true;
public static void setActive(boolean active){
BaseMouseListener.active = active;
}

protected abstract void doPerformAction(ActionEvent e);

@Override
public final void actionPerformed(ActionEvent e){
if(active){
doPerformAction(e);
}
}
}

您的听众必须实现 doPerformAction()而不是 actionPerformed()



(这在企业场景中可能会很糟糕,但是在单虚拟机模型中,如Swing,它应该能正常工作)


I've got a Swing application with a model and a view. In the view (GUI) there are a lot of components, each of them mapping to some property of a model object and displaying it's value.

Now there are some UI components that automatically trigger the updating of some model properties when their value changes in the UI. This requires me to reload the complete model in the UI. This way I'm entering an infinite update loop, as every model reload in the UI triggers another model reload.

I have a flag indicating the load process, which I'd like to use to temporarily suppress the listener notifications, while the UI fields are being set from the model. So my question is:

Is there a way to globally temporarily disable some component's listeners in Swing without removing and reattaching them?

解决方案

You could use a common base class for your listeners and in it, have a static method to turn the listeners on or off:

public abstract class BaseMouseListener implements ActionListener{

    private static boolean active = true;
    public static void setActive(boolean active){
        BaseMouseListener.active = active;
    }

    protected abstract void doPerformAction(ActionEvent e);

    @Override
    public final void actionPerformed(ActionEvent e){
        if(active){
            doPerformAction(e);
        }
    }
}

Your listeners would have to implement doPerformAction() instead of actionPerformed().

(This would be awful in an enterprise scenario, but in a single-VM model like in Swing, it should work just fine)

这篇关于如何暂时禁用Swing中的事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆