Why SWT, Why?

So in SWT there is this thing called a KeyListener.

One might expect something called a KeyListener to listen to events on keys. Well, you'd be right, unless you consider the CTRL or the SHIFT keys to be keys. According to the KeyListener, they are just state modifiers, and as such, KeyEvents are not thrown to registered KeyListeners when they are pressed. Weird huh? To capture those events you need to use the untyped KeyUp and KeyDown listeners. And to think, that's not even my rant for today.


If you register a KeyUp or a KeyDown listener to a Shell, you might expect that to provide events when you press keys independent of which component on the Shell has focus currently. Of course, you'd be wrong if you thought that. Assuming that you have, let's say, 5 widgets in a Shell, you need to tab 5 times (since SWT assigns initial widget focus to the first widget on the Shell). Then you can receive all the events you want on the Shell, until focus goes back to one of the other widgets. Oh, oh...I have a question!!!! HOW IS THAT USEFUL IN ANY APPLICATION?!?!?! It seems like a bad easter egg to add to your apps which are otherwise devoid of behaviour that makes no sense. Apparently no one ever wants to know if you are ctrl-clicking on something. And there could be some argument against ever having to do that....assuming of course, that SelectionEvent did what it was supposed to on all widgets and provided the key-modifier as a stateMask.

So here's the problem. You want to listen for keystrokes and you don't care which widget is receiving them. Let's say you want to display a generic help dialog if the user presses F1 like in the old days. Obviously, you don't want to have to register key listeners on every widget you add to your GUI. That would be stupid, ugly code, that would be painfully annoying to maintain. You might think that registering the listener on the Display might work. But it doesn't. Maybe you have to press tab one more time to receive keystroke events for that.

Ugh....I need a break.
I ran into a similar problem in trying to get the escape key to be the hot key for closing a dialog box. I wound up doing this:

// ESC key acts as the Cancel button.
Control[] widgets = shell.getChildren();

for (int i=0; i < widgets.length; i++) {
widgets[i].addKeyListener(new KeyAdapter() {

public void keyReleased(KeyEvent event) {

if (event.character == SWT.ESC) { shell.close();



And it worked?
Ahh I understand now, a loop for making all within a shell listen. Yeah I tried it and it works for me now. Thanks
I realize this is old, but take a look at Display.addFilter

Just implement Listener, and add the handleEvent method, and you're good to go for recieving events from anywhere in the display