gives a ClassCastException at runtime -
Exception in thread "main" java.lang.ClassCastException: [Ljava.awt.Component;
The return type of the getComponents() method in the Component class is Component. The attempted cast seems valid since all the components returned are in fact instances of JLabel as can be proved by calling getCLass() on each of the returned components. The ClassCastException is claiming that the components are instances of Component.
Changing the troublesome line to
corrects the problem.
Another possible change is to replace the last three lines of the program with
which also gives the desired result.
Trying something a bit different:
I.E. record the components added to the panel so that the getContents() call is no longer needed. The JLabels are stored in an array of Component references which is later casted to an array of JLabel.
It works so it can not be a casting problem, it must be something peculiar about getContents() !?!?
[ April 22, 2004: Message edited by: Carlos Failde ]