Tip: Styling Label Providers

Tip: Styling Label Providers

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:

search

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

mail1

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

[code lang=“java“]
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);
}
}
[/code]

Pretty basic right? Well, to get styled labels all we need to do is extend StyledCellLabelProvider (available since Eclipse 3.4):

[code lang=“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);
}
}
[/code]

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

mail21

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

Hope this helps and happy styling!

13 Comments

Sorry, the comment form is closed at this time.