SWT: Using the Font Dialog

This article was originally published in the EclipseZone Tips & Tricks section of Javalobby.org

Many applications have the need to provide a font-selection ability. Whether it is for a rich-style text editor, or simply so the user can customize the appearance of the application, font selection is a useful facility. Thankfully, it does come built in to SWT.

The class in question is the org.eclipse.swt.widgets.FontDialog class, and using it is quite straightforward. It is simply a matter of creating a new font dialog object, and then asking it to open.

Shell parentShell = // ...
FontDialog dialog = new FontDialog(parentShell);
dialog.open();

Now, obviously it's not very helpful to open the dialog and then not get any user input from it; it's important to know how to do that given changes to the SWT API to support newer, extended features. Originally, the FontDialog returned a FontData object, and took a FontData object when setting up as a default. Unfortunately, this didn't properly fit the shape of all platforms. Most notably, some X environments can have a font that is composed of multiple sets of font data. To properly support the structure needed by some X fonts, an array of FontData objects became the proper way to handle creating fonts from font data.

So, in otherwords, while the open() method returns a single FontData object, the more appropriate means of collecting font data to ensure multi-platform support is to use the getFontList() method after calling open() .

Shell parentShell = // ...
FontDialog dialog = new FontDialog(parent.getShell());
dialog.open();
Font f = new Font(parent.getDisplay(), dialog.getFontList());

The font dialog also supports the option of selecting a color via the setRGB(RGB) and getRGB() methods, although these aren't guaranteed to be available on all platforms (GTK/Gnome has no color selection for instance).

Here is a code example:

public void createPartControl(final Composite parent) {
	parent.setLayout(new GridLayout());
	final Button b = new Button(parent, SWT.PUSH);
	b.setText("Open Font Dialog");
	b.addListener(SWT.Selection, new Listener() {
		public void handleEvent(Event event) {
			FontDialog dialog = new FontDialog(parent.getShell());
			dialog.open();
			Font f = new Font(parent.getDisplay(), dialog.getFontList());
			b.setFont(f);
			parent.pack();
		}			
	});
}