Tree: addKeyListener(KeyListener lis) : Tree « org.eclipse.swt.widgets « Java by API






Tree: addKeyListener(KeyListener lis)


import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

public class MainClass {

  public static void main(String[] a) {
    
    final Display d = new Display();
    final Shell shell = new Shell(d);

    shell.setSize(250, 200);
    
    
    shell.setLayout(new FillLayout());
    final Tree tree = new Tree(shell, SWT.SINGLE);

    for (int i = 0; i < 3; i++) {
      TreeItem iItem = new TreeItem(tree, SWT.NONE);
      iItem.setText("Edit me by pressing F2 " + (i + 1));
      iItem.setExpanded(true);
    }

    final TreeEditor editor = new TreeEditor(tree);
    editor.horizontalAlignment = SWT.LEFT;
    editor.grabHorizontal = true;

    tree.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent event) {
        if (event.keyCode == SWT.F2 && tree.getSelectionCount() == 1) {
          final TreeItem item = tree.getSelection()[0];

          final Text text = new Text(tree, SWT.NONE);
          text.setText(item.getText());
          text.setFocus();

          text.addFocusListener(new FocusAdapter() {
            public void focusLost(FocusEvent event) {
              item.setText(text.getText());
              text.dispose();
            }
          });

          editor.setEditor(text, item);
        }
      }
    });
    
    shell.open();
    while (!shell.isDisposed()) {
      if (!d.readAndDispatch())
        d.sleep();
    }
    d.dispose();

  }
}
           
       








Related examples in the same category

1.new Tree(Composite parent, int style)
2.Tree: addSelectionListener(SelectionListener lis)
3.Tree: addTreeListener(TreeListener lis)
4.Tree: getSelection()