SWT Best Practices: Changing Fonts
Here is a widespread way of creating a label with a bold font:
Label label = new Label(shell, SWT.NONE); Font boldFont = new Font( label.getDisplay(), new FontData( "Arial", 12, SWT.BOLD ) ); label.setFont( boldFont ); label.setText("Bold Label");
Everything seems to be fine with this code. A Label is created with the default font “Arial”, the default size “12” and our desired style “BOLD”. So what’s the problem with this snippet?
With the above code that creates a BOLD font, you also specified the font name and size. The problem here is that you might not know which fonts are used on the system that will run your application. A major OS update might introduce new default fonts, and what was once a nice looking application will look like an alien. Or even worse, you want your SWT application to run on other platforms like web browsers or mobile devices that might not have the fonts at all.
So it all boils down to this simple rule: Don’t specify what you don’t want to change!
Here is a better way to do it: in this case it’s like getting the blueprint of the default font, making some changes and building a new font with the modified blueprint:
Label label = new Label(parent, SWT.NONE); FontDescriptor boldDescriptor = FontDescriptor.createFrom(label.getFont()).setStyle(SWT.BOLD); Font boldFont = boldDescriptor.createFont(label.getDisplay()); label.setFont( boldFont ); label.setText("Bold Label");
How would you implement a bold label? Do you have another way to deal with font styles? Please let us know in the comments below.
Update (11.02.2014): A blog post about Descriptors and managing SWT resources will follow soon.