Wednesday, March 30, 2016

How to select an item in a Jface TableViewer after a dialog becomes activated

Scenario : We have a Jface Dialog and a TableViewer or a TreeViewer on that dialog. after the dialog become active we want to select an item and want to fire the TableViewers selection listener.


Step 1. Add a selection listener to the TableViewer :

Note : You should do this in createDialogArea() method.

  getTableViewer().addSelectionChangedListener(new ISelectionChangedListener() {  
   @Override  
   public void selectionChanged(SelectionChangedEvent event) {  
   final Object selection = getSingleSelection(event.getSelection());  
   if (selection instanceof SomeObject) {  
    DoSomething();  
   }  
   }  
  });  
  }  


Step 2. Add a Shell Listner :(again in createDialogArea() method)

  getShell().addShellListener(new ShellAdapter()  
  {  
   @Override  
   public void shellActivated(ShellEvent e) {    
   super.shellActivated(e);  
   if (getLines().size()>0) {  
    getViewer().getControl().setFocus();  
    getTableViewer().setSelection(new StructuredSelection(get.getElementAt(0)),true);  
   }  
   }  
  });  



You are done ! now after the shell become active the first item of the TableViews will be selected and a selection listner will be fired . Enjoy!


No comments:

Post a Comment

5 Strategies for Getting More Work Done in Less Time

Summary.    You’ve got more to do than could possibly get done with your current work style. You’ve prioritized. You’ve planned. You’ve dele...