我有一个JLabel
的数组,并且有一个包含MouseAdapter
的列表的列表。这个想法是每个MouseAdapter
都有一个JLabel
列表。我想遍历这些列表,并将MouseAdapter
添加到每个JLabel
中。
JLabel[] labels;
ArrayList<ArrayList<MouseAdapter>> labelBehaviors;
但是,不能将
MouseAdapter
添加到JComponent
:必须将它们强制转换为MouseListener
,MouseMotionListener
等,然后再添加其相应方法。除了确定MouseAdapter
是否为MouseListener
,MouseMotionListener
等的实例,然后进行强制转换并以适当的方法添加它之外,是否有其他方法可以实现?我正在尝试这样做:
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 );
}
}
}
我不想做这样的事情,除非没有更简单的方法:
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 );
}
}
}
}
有没有更简单的方法,也许涉及
labelBehaviors
的类型签名? 最佳答案
MouseAdapter
实现所有三个接口。如果这些方法没有被覆盖,它们将什么也不做。简而言之,您可以跳过这些检查,因为由于声明,所有检查都将返回true
public abstract class MouseAdapter implements MouseListener, MouseMotionListener, MouseWheelListener
简化的循环是
for ( MouseAdapter behavior : labelBehaviors.get( i ) ) {
label.addMouseListener( behavior );
label.addMouseMotionListener( behavior );
label.addMouseWheelListener( behavior );
}