Open Source & Free  

TIP: Reordering Tabs

TIP: Reordering Tabs

Header Image

The Tabs class is pretty powerful and flexible as I mentioned before. One thing it doesn’t support is drag and drop to re-order the tabs. Here the flexibility of Codename One takes over and allows us to accomplish it.

We can use the builtin drag and drop support for components within the tabs container. This is exactly how the code below works. In the drop listener we block the the default processing of drop behavior so we can move the tab manually to the new location:

Form hi = new Form("Tabs", new BorderLayout());

Tabs t = new Tabs();

t.addTab("T1", new Label("Tab 1"));
t.addTab("T2", new Label("Tab 2"));
t.addTab("T3", new Label("Tab 3"));
t.addTab("T4", new Label("Tab 4"));

Container tabsC = t.getTabsContainer();
tabsC.setDropTarget(true);
for(Component c : tabsC) {
    c.setDraggable(true);
    c.addDropListener(e -> {
        e.consume();
        Component dragged = c;
        int x = e.getX();
        int y = e.getY();
        int i = tabsC.getComponentIndex(dragged);
        if(i > -1) {
            Component dest = tabsC.getComponentAt(x, y);
            if(dest != dragged) {
                Component source = t.getTabComponentAt(i);
                int destIndex = tabsC.getComponentIndex(dest);
                if(destIndex > -1 && destIndex != i) {
                    String title = t.getTabTitle(i);
                    t.removeTabAt(i);
                    t.insertTab(title, null, source, destIndex);
                }
            }
            tabsC.animateLayout(400);
        }
    });
}

hi.add(CENTER, t);
hi.show();

1 Comment

Leave a Reply