Eclipse SWT : Transform Keyboard key codes to String Format

While working on RCP application in eclipse, you need to capture and display the key or combination of key pressed by user. For example to capture key combination for a binding. If it is character key (printable) then its easy to get character presentation from pressed key code. But it would be little difficult to represent sequence of key or non printable key like “Insert”, “Backspace” etc.

The straight forward way is to have map between key integer code and its string presentation, liked explained in SWT snippet Print Key State, Code and Character.

There is optimized and standard way is available using eclipse JFace framework. It provides a utility class ,SWTKeySupport, for converting SWT events into key strokes and KeySequence, to represent zero or multiple key strokes.KeySequence provides standard string presentation of sequence of keys captured.

Here is the simple SWT program to demonstrate usage of these utility classes


import org.eclipse.jface.bindings.keys.KeySequence;
import org.eclipse.jface.bindings.keys.SWTKeySupport;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.bindings.keys.KeyStroke;

/**
*
* @author Yogesh Devatraj
*
*/
public class KeyStrokesToCharacter {

public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
final Label label = new Label (shell, SWT.NONE);
Rectangle clientArea = shell.getClientArea ();
label.setLocation (50, 50);
Listener listener = new Listener() {
public void handleEvent(Event e) {
/**
* Convert Keyboard event key codes to character format.
*/
int accelerator = SWTKeySupport.convertEventToUnmodifiedAccelerator(e);
KeyStroke keyStroke = SWTKeySupport.convertAcceleratorToKeyStroke(accelerator);
KeySequence sequence = KeySequence.getInstance(keyStroke);
if(!sequence.isEmpty()) {
label.setText(sequence.toString());
label.pack();
shell.redraw();
System.out.println(sequence.toString());
}
}
};
shell.addListener(SWT.KeyDown, listener);
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}




The result window will be


image

Comments

Post a Comment

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester