ptg7068951
Using Image Icons and Toolbars 227
When you run the application, as shown earlier in Figure 16.2, a frame
contains three sliders that represent the amount of red, green, and blue in a
panel along the bottom edge of the frame.
Adjust the values of each slider to change the color that is displayed. In
Figure 16.2, the application is used to create North Texas Mean Green (red 50,
green 150, and blue 50). This shade inspires alumni of the University of North
Texas to leap to our feet at sporting events and make ferocious eagle-claw
hand gestures that turn visiting teams yellow (red 255, green 255, orange 0).
Using Image Icons and Toolbars
Oneof the easiest ways to improve the visual appeal of a GUI is to use
icons, small images used to identify buttons and other parts of an interface.
With many of the components in the Swing class library, you can label a
component with an image instead of text by using the ImageIconclass in
the javax.swingpackage.
You can create an ImageIconfrom a file on your computer by calling the
ImageIcon(String)constructor method. The argument to the method is
either the name of the file or its location and name, as in these examples:
ImageIcon stopSign = new ImageIcon(“stopsign.gif”);
ImageIcon saveFile = new ImageIcon(“images/savefile.gif”);
The graphics file used to create the image icon must be in GIF, JPEG, or
PNG format. Most are in GIF format which is well suited to displaying
small graphics with a limited number of colors.
The ImageIconconstructor loads the entire image from the file immediately.
You can use image icons as labels and buttons by using the
JLabel(ImageIcon)and JButton(ImageIcon)constructor methods, as in
the following example:
ImageIcon siteLogo = new ImageIcon(“siteLogo.gif”);
JLabel logoLabel = new JLabel(siteLogo);
ImageIcon searchWeb = new ImageIcon(“searchGraphic.gif”);
JButton search = new JTextField(searchWeb);
Several components can have an icon and a text label. The following state-
ment creates a button with both:
JButton refresh = new JButton(“Refresh”,
“images/refreshIcon.gif”);
CAUTION
Although some operating sys-
tems use the \character to
separate folders and filenames,
theImageIconconstructor
requires the /character as a
separator.