Search code examples
javaswtdisposeeclipse-gefdraw2d

How to dispose of an SWT Font set on a Draw2D Label?


In a GEF editor, I have the following EditPart:

public class MyLabelEditPart extends AbstractGraphicalEditPart {

@Override
protected IFigure createFigure() {
    return new Label();
}

@Override
protected void refreshVisuals() {
    MyModel model = (MyModel) getModel();
    Label figure = (Label) getFigure();
    EditPart parent = getParent();

    Font font = new Font(Display.getCurrent(), "sansserif", 11, SWT.BOLD);
    figure.setFont(font);
    figure.setForegroundColor(ColorConstants.darkGray);
    figure.setText(model.getValueString());
    parent.refresh();
}

All works fine with most models, but - you will have spotted the error already - I never dispose of the font. So, with a large-ish model of 10k+ tokens, this throws an org.eclipse.swt.SWTError: No more handles. At least I think (hope) this is what causes the error.

Now I cannot figure out how to dispose the font, as the figure for the EditPart is a Draw2D Label, not an SWT Widget. How can I make sure the dreaded error can be circumvented?


Solution

  • Apart from Baz' solution to make the font a static field, a good solution is to use a JFace FontRegistry, as detailed in this strangeoptics blog post.