Search code examples
javaswingmouseeventevent-listenerjcomponent

Add all elements of a list of MouseAdapter to a JComponent


I have an array of JLabels, and I have a list of lists holding MouseAdapters. The idea is that there is one list of MouseAdapters for each JLabel. I want to iterate over these lists and add the MouseAdapters to each JLabel.

JLabel[] labels;
ArrayList<ArrayList<MouseAdapter>> labelBehaviors;

However, you can't add MouseAdapters to a JComponent: they have to be cast to MouseListener, MouseMotionListener, etc. and then added with their corresponding methods. Is there a way that I can do this, other than determining if the MouseAdapter is an instance of MouseListener, MouseMotionListener, etc., then casting it and adding it with the proper method?

I'm trying to do this:

for ( int i = 0; i < LABEL_COUNT; i++ ) {
  JLabel label = labels[i];
  if ( label != null ) {
    // Add associated behaviors to the label.
    for ( MouseAdapter behavior : labelBehaviors.get( i ) ) {
      // addMouseEventListener() doesn't exist...
      label.addMouseEventListener( behavior );
    }
  }
}

I don't want to do something like this, unless there isn't an easier way:

for (int i = 0; i < LABEL_COUNT; i++ ) {
  JLabel label = labels[i];
  if ( label != null ) {
    // Add associated behaviors to the label.
    for ( MouseAdapter behavior : labelBehaviors.get( i ) ) {
      // Check type of behavior.
      if ( behavior instanceof MouseListener ) {
        label.addMouseListener( (MouseListener) behavior );
      } else if ( behavior instanceof MouseMotionListener ) {
        label.addMouseMotionListener( (MouseMotionListener) behavior );
      } else if ( behavior instanceof MouseWheelListener ) {
        label.addMouseWheelListener( (MouseWheelListener) behavior );
      }
    }
  }
}

Is there a simpler way, perhaps involving the type signature of labelBehaviors?


Solution

  • A MouseAdapter implements all three interfaces. If the methods aren't overridden, they will do nothing. In short, you can skip these checks since all of them will return true because of the declaration

    public abstract class MouseAdapter implements MouseListener, MouseMotionListener, MouseWheelListener
    

    The simplified loop is

    for ( MouseAdapter behavior : labelBehaviors.get( i ) ) {
        label.addMouseListener( behavior );
        label.addMouseMotionListener( behavior );
        label.addMouseWheelListener( behavior );
    }