I have an array of JLabel
s, and I have a list of lists holding MouseAdapter
s. The idea is that there is one list of MouseAdapter
s for each JLabel
. I want to iterate over these lists and add the MouseAdapter
s to each JLabel
.
JLabel[] labels;
ArrayList<ArrayList<MouseAdapter>> labelBehaviors;
However, you can't add MouseAdapter
s 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
?
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 );
}