views:

142

answers:

1

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);
    }
+3  A: 

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.

pstanton
Generally on state change (as opposed to input) events it is more robust to completely ignore the event object. (Don't be confused about performance - think about how many cycles you are using compared to *millions* an average CPU can do in a millisecond).
Tom Hawtin - tackline
@Tom: is that a comment on my answer, or his question?
pstanton
@pstanton A bit of both.
Tom Hawtin - tackline
ok, well your point isn't entirely clear.
pstanton