Dynamically populating a Combo based on shift key

In a recent project I had a combo box that I wanted to add additional entries to if they clicked on it with the shift key pressed.

This is to allow to select entries that would not normally be displayed (for example, out dated values that could actually be selected).

To do this, I added key-up & key-down listeners on the Display object and populated the Combo based on the shift key state.

My Listener object (keyListener) was global, because I wanted to remove the listener when the parent control was disposed.

[java]
keyListener = new Listener() {

@Override
public void handleEvent(Event event) {

// if shift is pressed when the combo is expanded,
// populate the combo with entries not normally displayed.
if (event.keyCode == SWT.SHIFT && event.widget == combo) {
if (event.type == SWT.KeyDown) {
populateCombo(true);
}
}
}
};

// Add the key listener to the Display object so the key modifier is global.
Display d = combo.getDisplay();
d.addFilter(SWT.KeyDown, keyListener);
d.addFilter(SWT.KeyUp, keyListener);

populateCombo(false);

[/java]

This routine will populate the combo … if the override parameter is true, then the normally hidden items will be added.

[java]
private void populateCombo(boolean override) {

combo.removeAll();

combo.add("Item 1");
combo.add("Item 2");
combo.add("Item 3");
combo.add("Item 4");
// If overridden, add the normally hidden entries
if (override) {
combo.add("Item 5");
combo.add("Item 6");
combo.add("Item 7");
}
}
[/java]

And, so we don’t leave code running when we don’t want it to, we remove the listeners when the enclosing control is disposed.
[java]
/**
* @see org.eclipse.jface.dialogs.DialogPage#dispose()
*/
@Override
public void dispose() {

Display d = combo.getDisplay();

d.removeFilter(SWT.KeyDown, keyListener);
d.removeFilter(SWT.KeyUp, keyListener);

super.dispose();
}
[/java]

Related posts ...
I'm in the process of updating the help text for my RCP and have found
Normally, when you view the property pages on Eclipse items, the pages show up in
I had a very frustrating day at work today ... nothing was working right ...
It took a bit of experimentation, but I think this routine could be used to

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.