Sunday, November 8, 2009

What did I learn today - Adding key listeners to trees and tables (SWT/JFace)

I wanted my trees and tables to listen to DEL key so that when user presses it, the selected nodes in the tree or the selected cells in the table would get deleted. I was looking for the method to add key listener to the table/tree viewer, but found that I need to add it to the viewer control.

Below is the code to add listener to the delete key on your tree viewer.

this.treeViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(final KeyEvent e) {
if (e.keyCode == SWT.DEL) {
IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection();
if (selection.isEmpty()) {

// Business logic to handle deletion - remove from model, view etc.,

You can do it similarly for other viewers (table viewer etc.,) or to listen to other keys also.

If you are working directly with SWT, you will add listener directly to the tree/table (i.e the control itself) like tree.addKeyListener(), table.addKeyListener() etc., You can add this to any control in SWT.

No comments: