Java – EventListenerList firing order

event-listenerjavaswing

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

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

Best Answer

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.

Related Topic