Tuesday, September 27, 2011

JFace: A Viewer For Composites

JFace comes along with these nice Viewers. They build up the next layer ontop of the standard widgets. You are setting you business objects into a Viewer and it knows from its Label- and ContentProvider how to handle them.

A Table got its TableViewer a Tree its TreeViewer, ...
Wouldn't it bee nice to have such a Viewer for Composites?
You stuff you business object into it like a Person object and it knows how to display it. The next time you stuff a Project object into it and you see an UI representation of it.

If you like the idea, have a look at my classes and read further.
Viewer:                CompositeViewer
ContentProvider:  ICompositeProvider
LabelProvider:     Your Composites that draws the UI for the business object.
                            They have to implement the interface IInput or extends the
                            class CompositeInput.


How to use the CompositeViewer:

Instantiate it and give it a size, because it is empty.
 compViewer = new CompositeViewer(parent, SWT.BORDER);  
 compViewer.setCompositeProvider(new CompositeProviderPersonProject());  
 compViewer.setLayoutData(createGridDataForInputFields(200, 200));  

The ICompositeContentProvider implementation looks like this.
 public class CompositeProviderPersonProject implements ICompositeProvider {  
      @Override  
      public Class<?> getCompositeClass(Object o) {  
           if(o.getClass() == Person.class) {  
                return CompositePerson.class;  
           }  
           if(o.getClass() == Project.class) {  
                return CompositeProject.class;  
           }  
           return null;  
      }  
 }  

If you place a Person object.
 compViewer.setInput(new Person("strange", "optics", 35, 'M'));  


If you place a Project object.
 compViewer.setInput(new Project("Strangewt", "More programming convinience!"));  

No comments:

Post a Comment