EventListenerList 触发顺序 [英] EventListenerList firing order

查看:16
本文介绍了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 建议的链接方法更可靠地强制执行正确的顺序.例如,SubPanelChangeListener 可以简单地将事件转发给父级.

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