Previous Page
Next Page

4.4. Resource Management

Consistent with the design of the rest of SWT, colors, fonts, and images are also thin wrappers around their platform counterparts that must be explicitly destroyed when no longer needed.

The basic rule is: If you access a color, font, or image from somewhere else, you don't need to worry about it. On the other hand, if you create the resource, then you must destroy it when you are done with it. For any resources that you anticipate routinely accessing within your application, consider creating a resource manager to manage them and then destroy all the resources when your application exits.

4.4.1. Colors

Colors are created for a specific device (which can be null, representing the default device) and are described by three integer values representing each color component (red, green, and blue) in the range of 0 to 255 (e.g., new Color(null, 255, 0, 0) creates the color red). The foreground and background colors of widgets can be set using the setForeground() and setBackground() methods, respectively.

To use one of the colors predefined by the platform, such as window background color or button background color, you can use the Display.getSystemColor(int) method, which takes the identifier of the desired color as an argument. You don't need to dispose of any colors that you get this way.

4.4.2. Fonts

As with colors, fonts are also created for a specific device and are described by a font name (e.g., Arial, Times, etc.), a height in points, and a style (and combination of SWT.NORMAL, SWT.BOLD, or SWT.ITALIC). Fonts can be either created by specifying the name, height, and style directly or by referencing a FontData object that encodes those three values. For example, new Font(null, "Arial", 10, SWT.BOLD) creates a 10-point, bold Arial font. A widget's font can be set using the setFont() method.

4.4.3. Images

Images are frequently used in toolbars, buttons, labels, trees, and tables. Eclipse supports loading and saving images in a variety of common file formats such as GIF, JPEG, PNG, BMP (Windows bitmap), and ICO (Windows icon). Some formats, such as GIF, support transparency, which makes them ideal for use in toolbars and as item decorators in lists and tables.

Images are created for a specific device and are usually either loaded from a specific file or created from a device-independent ImageData object. For example, both of the following are equivalent:

Image img = new Image(null, "c:\\my_button.gif")
ImageData data = new ImageData("c:\\my_button.gif");
Image img = new Image(null, data);

On widgets that support images as part of their content, such as labels and buttons, use the setImage() method to set the widget's images. For information on image caching and ImageDescriptor, see Section 7.7, Image Caching, on page 315.


Previous Page
Next Page