Can someone explain this casting behaviour?
Ok, so there are two classes, C1 and C2.
C1 contains the following method:
protectedstaticfinal PersistentCheckBoxMenuItem[] getCollections(){
Component components[] = ((JMenu)menubar.getComponent(3)).getMenuComponents();
return (PersistentCheckBoxMenuItem[]) Arrays.copyOfRange(components, 6, components.length);;
}
C2 contains the following Action:
protectedclass CollectionsStateChangeActionextends AbstractAction{
privateboolean state;
protected CollectionsStateChangeAction(String title, String desc,
Integer accelerator, Integer mask,boolean state){
/* initializer code left out for purpose of example */
this.state = state;
}
publicvoid actionPerformed(ActionEvent e){
// obtain current menu collection list
// (PersistentCheckBoxMenuItem extends JCheckBox)
PersistentCheckBoxMenuItem colls[] = Silk.getCollections();
// loop through list and (de)select every item
for (int i = 5; i < colls.length; i++){
colls[i].setSelected(state);
}
}
}
Trying to fire the action gives the following exception:
Exception in thread"AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.awt.Component; cannot be cast to [Lsilk.PersistentCheckBoxMenuItem;
BUT, here's what I don't get.
If I change the above code chunks so the cast occurs in the Action instead:
C1:
protectedstaticfinal Component[] getCollections(){
Component components[] = ((JMenu)menubar.getComponent(3)).getMenuComponents();
return Arrays.copyOfRange(components, 5, components.length);
}
C2:
protectedclass CollectionsStateChangeActionextends AbstractAction{
privateboolean state;
protected CollectionsStateChangeAction(String title, String desc,
Integer accelerator, Integer mask,boolean state){
/* initializer code left out for purpose of example */
this.state = state;
}
publicvoid actionPerformed(ActionEvent e){
// obtain current menu collection list
Component colls[] = Silk.getCollections();
// loop through list and (de)select every item
for (int i = 0; i < colls.length; i++){
((PersistentCheckBoxMenuItem)colls[i]).setSelected(state);
}
}
}
..then now everything works fine!
Why on earth would shifting the cast to the Action make things work? I tried putting the 'Arrays.copy....' result in C1's method into a Component[] variable andthen casting it and returning it, and that doesn't work either.
I'm on JRE 6, and I'm puzzled :)

