Tip: Styling Label Providers

March 10, 2009 | 1 min Read

Were you ever curious how to get those pretty colored labels in your JFace viewers you see all over Eclipse? For example, the blue counter label in the search results view:

Well, I’ll tell you how! Let’s start with famous RCP Mail example:

Let’s look at the current label provider in the RCP Mail example:

class ViewLabelProvider extends LabelProvider {

public String getText(Object obj) { return obj.toString(); }

public Image getImage(Object obj) { String imageKey = ISharedImages.IMG\_OBJ\_ELEMENT; if (obj instanceof TreeParent) imageKey = ISharedImages.IMG\_OBJ\_FOLDER; return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey); } } ```

Pretty basic right? Well, to get styled labels all we need to do is extend [StyledCellLabelProvider](https://help.eclipse.org/ganymede/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/viewers/StyledCellLabelProvider.html) (available since Eclipse 3.4):

```java class ViewLabelProvider extends StyledCellLabelProvider { public void update(ViewerCell cell) { Object obj = cell.getElement(); StyledString styledString = new StyledString(obj.toString());

if(obj instanceof TreeParent) { TreeParent parent = (TreeParent) obj; styledString.append(" (" + parent.getChildren().length + ")", StyledString.COUNTER\_STYLER); }

cell.setText(styledString.toString()); cell.setStyleRanges(styledString.getStyleRanges()); cell.setImage(getImage(obj)); super.update(cell); }

public Image getImage(Object obj) { String imageKey = ISharedImages.IMG\_OBJ\_ELEMENT; if (obj instanceof TreeParent) imageKey = ISharedImages.IMG\_OBJ\_FOLDER; return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey); } } ```

If you do that, the RCP Mail example will look like this now:

[](images/mail21.png)

This just scratches the surface of what is possible with owner draw, styled strings and styled label providers.

Hope this helps and happy styling!