Thursday, May 15, 2008

Creating a Minimum Width Constraint on an SWT SashForm

3 comments
My friend Matt encouraged me to blog a quick snippet of code that many SWT coders might find useful.

If you've used the SWT SashForm, you know it's a nice widget in that it saves you a bit of work that you would do using a traditional Sash. One of the things I expected to get for "free" was the ability to limit how far the sash could expand or collapse a single control, or eseentially constrain the sash from completely hiding any number of it's child controls. To my surprise, I found that this is not a feature of the SashForm.

I have figured out how to create that behavior, by adding a selectionListener to the sash on the sashform. I have to give most of the credit to Duong Nguyen, who posted a partial solution to my problem here.

Without further adue, here's the code:

// Set a minimum width on the sash so that the
// controls on the left are always visible.

// First, find the sash child on the sashform...
Control[] comps = sashform.getChildren();
for (Control comp : comps){

if (comp instanceof Sash){

// My limit is derived from the size of a
// toolbar; yours can be any size you wish ...

int limit = 10;

for (ToolItem item : view.getParent().getItems()){
limit += item.getWidth();
}

final int SASH_LIMIT = limit;
final Sash sash = (Sash)comp;

sash.addSelectionListener (new SelectionAdapter () {
public void widgetSelected (SelectionEvent event) {
Rectangle rect = sash.getParent().getClientArea();
event.x = Math.min (Math.max (event.x, SASH_LIMIT), rect.width - SASH_LIMIT);
if (event.detail != SWT.DRAG) {
sash.setBounds (event.x, event.y, event.width, event.height);
sashform.layout();
}
}
});
}
}

Hope this is useful!
kindest regards,
G