Vaadin 7: Setting the Nth Element in a Container Layout

VAADIN's AbstractLayout, the parent of Horizontal and VerticalLayouts, contains methods to add components to the back and in front of existing ones, but not in the middle of them. It should be pretty obvious how to perform this task, but it is not. Once a component is moved to another layout it is removed from the original, so an iteration will not work as the list of components changes in size in each iteration.

Here is the code:

public void addNthComponent(
            AbstractOrderedLayout layout,
            Component c,
            int pos) {
        HorizontalLayout nc = new HorizontalLayout();

        int count = layout.getComponentCount();
        for (int i = 0; i < pos; i++) {
            Component ci = layout.getComponent(0);
            nc.addComponent(ci);
        }
        nc.addComponent(c);
        for (int i = pos; i < count; i++) {
            Component ci = layout.getComponent(0);
            nc.addComponent(ci);
        }

        for (int i=0;i<count+1;i++)
        {
            layout.addComponent(nc.getComponent(0));
        }
    }

Comments

Popular posts from this blog

Vaadin 7: Detect Enter Key in a TextField

Qt Signals and Slots, Connecting and Disconnecting

JAVA JPA WITH HIBERNATE AND H2 Tutorial