1

We have a standard GUI control with a bunch of default listeners like that:

class OurControl extends Control {

    OurControl() {
         addMouseWheelListener(new DefaultMouseWheelListener());
    }

}

The defaults are good for the standard use-cases, but now the customer wants to use their own listeners in some cases. I'm searching for the most elegant way to achieve that.

Idea 1: (it just feels weird to me, and I don't like to maintain a list of listeners that might be removed)

class OurControl extends Control {

    MouseWheelListener defaultListener = new DefaultMouseWheelListener();

    OurControl() {
         addMouseWheelListener(defaultListener);
    }

    void removeDefaultMouseWheelListener() {
         removeMouseWheelListener(defaultListener);
    }
}

Idea 2: (I like this one, even though technically speaking the listener stays where it is; it at least follows the standard bean pattern)

class OurControl extends Control {

    public boolean enableMouseWheel = true;

    OurControl() {
         addMouseWheelListener(new MouseWheelListener() {
             void mouseWheelMoved(final MouseWheelEvent e) {
                 if (enableMouseWheel)
                     doMagic();
             }
         });
    }
}

What is a good way to achieve this goal?

1

Option 2 is by far the best, if I correctly understand what you mean.

Your default mouse wheel listener presumably does a certain job; let's say, it scrolls.

Your client's need to set their own listener tells me that they don't want you to scroll, so that they can use the mouse wheel for something else.

But you see, how you achieve this scrolling on mouse wheel is none of their business, and the fact that you achieve it with a mouse wheel listener is just a little implementation detail that they need not and should not be concerned with. So, instead, your control should offer a "Scroll on Mouse Wheel" option, controlling this aspect of its behavior, which your client may set to false if they don't like it.

Then, your client is also free to add their own mouse wheel listener to do their own stuff, like perhaps zoom instead of scroll. If they forget to cancel the "Scroll on Mouse Wheel" option, they will get both behaviors, and that's perfectly understandable.

0

An alternative approach I've seen is listeners having the ability to cancel subsequent listeners. For example, DOM Events supports this.

This relies on listeners being called in a well-defined order. I think it's pretty standard that listeners are called in reverse order of registration, but check your particular framework.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.