Search code examples
javaarraysjcomponentjtoolbar

Adding components into Component[] array


This seems so basic, but for some reason I can't get it to work.

I have the following code:

Component[] AddEditDelete = ToolbarPool.getDefault().findToolbar("AddEditDelete").getComponents();
for (Component component : AddEditDelete) {
    component.setEnabled(false);
}

Component[] Navigation = ToolbarPool.getDefault().findToolbar("Navigation").getComponents();
for (Component component : Navigation) {
    component.setEnabled(false);
}

Component[] ListFind = ToolbarPool.getDefault().findToolbar("ListFind").getComponents();
for (Component component : ListFind) {
    component.setEnabled(false);
}

What I would want to do is create a single Component[] c array and then into that array, add all the components from the Toolbars.

My intuitive approach of

Component[] c;
c.add(stuff);

Didn't seem to work. So I assume you do it else-how.

edit1: My most recent attempt with ArrayList > Component didn't work =(

ArrayList c = new ArrayList();
c.add(ToolbarPool.getDefault().findToolbar("AddEditDelete").getComponents());
c.add (ToolbarPool.getDefault().findToolbar("Navigation").getComponents());
Component[] cc = (Component[]) c.toArray();
for (Component component : cc) {
    component.setEnabled(false);
}

edit2: Silly me, trying to use ArrayList without a type. This works, but it will still be quite a few lines of code:

ArrayList<Component> c = new ArrayList<Component>();
for (int i = 0; i < ToolbarPool.getDefault().findToolbar("AddEditDelete").getComponents().length; i++) {
    c.add(ToolbarPool.getDefault().findToolbar("AddEditDelete").getComponent(i));
}
for (int i = 0; i < ToolbarPool.getDefault().findToolbar("Navigation").getComponents().length; i++) {
    c.add(ToolbarPool.getDefault().findToolbar("Navigation").getComponent(i));
}
for (Component component : c) {
    component.setEnabled(false);
}

Is there a way to shorten the amount of lines of code?


Solution

  • You need to create the array before you can use it (you need to know the array size in advance):

    Component[] c = new Components[10];
    c[0] = stuff;
    

    It may be a better idea to use a List instead (more flexible, better API):

    List<Component> components = new ArrayList<Components>
    components .addAll(Arrays.asList(ToolbarPool.getDefault().findToolbar("AddEditDelete").getComponents()));
    components .addAll(Arrays.asList(ToolbarPool.getDefault().findToolbar("Navigation").getComponents()));
    for (Component component : components) {
        component.setEnabled(false);
    }