Switch the (JTabbedPane[])
cast to (Component[])
. If you hover over the getComponents()
method, you'll see it returns Component[]
If you want to convert that Component[]
to JTabbedPane[]
, you need to do it manually, as well as making sure to check for mistakes along the way (making sure its a JTabbedPane before adding it to a JTabbedPane[])
JTabbedPane[] panes = convertComponents(getComponents());
private JTabbedPane[] convertComponents(Component[] comps) {
JTabbedPane[] panes = comps.length > 0? new JTabbedPane[comps.length] : null;
if(panes != null)
for(int i = 0; i < panes.length; i++) {
if(comps[i] instanceof JTabbedPane)
panes[i] = (JTabbedPane) comps[i];
}
return panes;
}
Although this isn't the most efficient, because for each item that isn't a JTabbedPane in getComponents(), there will be an empty spot in your JTabbedPane array, which you then have to clean up.
JTabbedPane[] panes = comps.length > 0? new JTabbedPane[comps.length] : null;
This first checks if the Component[] passed through the parameters has 1 or more spaces. If not, dont bother initializing with an instance.
if(panes != null)
Since theres a chance panes
could initialize as null
, we much check before trying to use it
for(int i = 0; i < panes.length-1; i++) {
Since Component[] comps
and JTabbedPane[] panes
have the same size, it doesn't matter which length you use, as long as we know how many times to loop.
if(comps[i] instanceof JTabbedPane)
This is what I meant where I said "if the component isn't a JTabbedPane
, you will have a null space in your array". This will check if it's a JTabbedPane
before putting it in our panes array. If not, it's ignored completely, and that space in panes
is left as null
After the loop is complete, it will return the array we just made.