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

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

问题描述

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

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.

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

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.

我有一个指示加载过程的标志,我想用它来暂时抑制侦听器通知,同时从模型设置 UI 字段.所以我的问题是:

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:

有没有办法全局临时禁用 Swing 中某些组件的侦听器,而无需移除和重新附加它们?

推荐答案

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

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);
        }
    }
}

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

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

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

(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天全站免登陆