EventListenerList触发顺序 [英] EventListenerList firing order

查看:229
本文介绍了EventListenerList触发顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swing应用程序中,我有许多子面板,每个子面板都听一个 JSlider 。周围的父面板也会监听所有子面板。为了在下面的示例中获得一致的结果,我必须首先添加父项,然后然后添加本地侦听器。考虑到 <中规定的顺序,这是有道理的。 code> EventListenerList 并在此文章。我可以依赖该订单,还是应该安排发送不同的活动?

In a Swing application, I have a number of sub-panels, each listening to a single JSlider. The surrounding parent panel also listens to all the sub-panels. To get consistent results in the example below, I had to add the parent first and then the local listener. This makes sense, given the order prescribed in EventListenerList and explained in this article. Can I rely on that order or should I arrange to send a different event?

class SubPanel extends JPanel implements ChangeListener {

    private final JSlider slider = new JSlider();
    private final JLabel label = new JLabel();
    private final String name;
    private float value;

    public SubPanel(String name, float value, ChangeListener parent) {
        this.name = name;
        this.value = value;
        ...
        slider.addChangeListener(parent);
        slider.addChangeListener(this);
    }
    ...
}

附录:讨论在 EventListenerList 似乎是实施建议而非保证。 pstanton 建议的链接方法可以更可靠地执行正确的订单。例如, SubPanel ChangeListener 可以简单地将事件转发给父级。

Addendum: the discussion in EventListenerList appears to be implementation advice rather than a guarantee. The chaining approach suggested by pstanton enforces the correct order more reliably. For example, the SubPanel's ChangeListener can simply forward the event to the parent.

    @Override
    public void stateChanged(ChangeEvent e) {
        ...
        parent.stateChanged(e);
    }


推荐答案

自JSlider和JComponent等没有提到听众通知的顺序,我会毫不犹豫地依赖它,至少没有对JRE的每个后续版本进行全面测试。

Since the documentation for JSlider and JComponent etc don't mention the order of listener notification, I would hesitate to rely on it, at least without thorough testing on each subsequent version of the JRE.

如果你确实需要依赖顺序,考虑设置一个监听器链,即监听器将通知监听器两个等。

If you really need to rely on the order, consider setting up a chain of listeners, ie Listener one will notify listener two etc.

这篇关于EventListenerList触发顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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