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.

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);

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

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");
	}
}

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.

/**
 * @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();
}

Leave a Reply

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