Working with fonts in Eclipse ui plugins is sometimes a bit indirectly.
For example, if you want to set an element’s font to bold, you can not simply set item.setBold() or item.getFont().setBold().

The best way to get around this, is to :

  1. get a default font from any element
  2. create a font descriptor from it,
  3. set the style of the font descriptor to bold,
  4. get a new font instance from this descriptor, and
  5. set this font to your element of choice.

Doing this, you can cache the font instance to reuse it later one.

The method getFont() allows to get a styled font based on the font of an swt control element:

    private Font getFont(Control control, int style) {
        Display display = Display.getCurrent();
        FontDescriptor fontDescriptor = FontDescriptor.createFrom(control.getFont());
        return fontDescriptor.setStyle(style).createFont(display);

For example, this can be used to get a bold font to be set for tree items based on the font of the enclosing tree:

Control control = treeViewer.getTree();
Font fontBold = getFont(control, SWT.BOLD);

This more a reminder for myself, but perhaps, someone will find this usefull as well…

Bold Font in Eclipse JFace Viewer

Post navigation