For a JFace (table) viewer to work, a ContentProvider and a LabelProvider is essential.
When creating a viewer, a default LabelProvider (an instance of LabelProvider
) is already set. This implementation uses toString()
to obtain a textual representation of the element.
A ContentProvider needs to be explicitly set. It is used to translate from the applications domain model to the viewers model. In case of the TableViewer
, the viewer expects a flat array of the elements that should be displayed. Each element represents one row of the TableViewer.
If your domain model already uses an array or collection, you can use the predefined ArrayContentProvider
.
To show a list of Person
s for example you would configure the viewer like this:
Person[] persons = ...
viewer.setContentProvider( ArrayContentProvider.getInstance() );
viewer.setInput( persons );
Suppose that persons are held in a PersonRegistry
you would rather configure the viewer with a custom ContentProvider that is able to extract persons from the registry:
PersonRegistry registry = ...
viewer.setContentProvider( new PersonContentProvider() );
viewer.setInput( registry );
class PersonContentProvider implements IStructuredContentProvider {
PersonRegistry registry;
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.registry = ( PersonRegistry )newInput;
}
public Object[] getElements(Object inputElement) {
return registry.getPersons();
}
...
}
Finally, setInput()
is meant to supply the application model. The inputChanged()
method of the ContentProvider must be able to cope with what was passed to setInput()
. Also note, that setInput()
must only be called after a content provider was set, otherwise an exception will be thrown.