Thursday, August 26, 2010

SWT, Tabfolder and ScrolledComposite

Every time I have to create a scrolled tabfolder, it is the same. I have to fiddle around to make it work nicely. Around the net I can't find a good and complete example.

So here is how I solved it. Didn't have time to clean the code up. Remove objects you don't need and if you have troubles, just ping me. Hope this helps someone.
Here we go:


// create the tab folder
final CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM);
folder.setUnselectedCloseVisible(false);
folder.setLayout(new FillLayout());

// for every Tab object create a tab
List orderedTabs = form.getOrderedTabs();
boolean first = true;
for( Tab orderedTab : orderedTabs ) {
// the tabitem
CTabItem tab = new CTabItem(folder, SWT.NONE);
tab.setText(orderedTab.text);
if (first) {
// select the first tab
folder.setSelection(tab);
first = false;
}

// we want the content to scroll
final ScrolledComposite scroller = new ScrolledComposite(folder, SWT.V_SCROLL);
scroller.setLayout(new FillLayout());

// the actual content of the tab
Composite tabComposite = new Composite(scroller, SWT.NONE);
tabComposite.setLayout(new MigLayout(orderedTab.layoutConstraints, orderedTab.colConstraints));

// which goes as content to the scrolled composite
scroller.setContent(tabComposite);
scroller.setExpandVertical(true);
scroller.setExpandHorizontal(true);
scroller.setMinHeight(folder.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
scroller.addControlListener(new ControlAdapter(){
public void controlResized( ControlEvent e ) {
// recalculate height in case the resize makes texts
// wrap or things happen that require it
Rectangle r = scroller.getClientArea();
scroller.setMinHeight(folder.computeSize(SWT.DEFAULT, r.height).y);
}
});

// the scroller gets the control of the tab item
tab.setControl(scroller);


// add things to the tab composite
List< ? extends FormElement> orderedElements = orderedTab.getOrderedElements();
for( FormElement orderedGuiElement : orderedElements ) {
FormGuiElement formGui = FormGuiFactory.createFormGui(orderedGuiElement);
formGui.makeGui(tabComposite);
}
}
Post a Comment