Java Reference
In-Depth Information
18.2
Icons and Scroll Bars
I ICONS .
Bumper sticker
Icons
JLabel s , JButton s , and JMenuItem s can have icons. An icon is simply a small
picture, although it is not required to be small. The label, button, or menu item may
have just a string displayed on it, just an icon, or both (or nothing at all). An icon is an
instance of the ImageIcon class and is based on a digital picture file. The picture file
can be in almost any standard format, such as .gif, .jpg, or .tiff.
The class ImageIcon is used to convert a picture file to a Swing icon. For example,
if you have a picture in a file named duke_waving.gif, the following will produce an
icon named dukeWavingIcon for the picture duke_waving.gif:
icon
ImageIcon
ImageIcon dukeIcon = new ImageIcon("duke_waving.gif");
The file duke_waving.gif should be in the same directory as the class in which this
code appears. Alternatively, you can use a complete or relative pathname to specify the
picture file. Note that the picture file is given as a value of type String that names
the picture file. The file duke_waving.gif and other picture files we will use in this
chapter are all provided on the website that accompanies this text.
You can add an icon to a label with the method setIcon, as follows:
JLabel dukeLabel = new JLabel("Mood check");
setIcon
dukeLabel.setIcon(dukeIcon);
Alternatively, you give the icon as an argument to the JLabel constructor,
as follows:
JLabel dukeLabel = new JLabel(dukeIcon);
You can leave the label as created and it will have an icon but no text, or you can add
text with the method setText, as follows:
setText
dukeLabel.setText("Mood check");
Icons and text may be added to JButton s and JMenuItem s in the same way as they
are added to a JLabel . For example, the following is taken from Display 18.4, which is
a demonstration of the use of icons:
JButton happyButton = new JButton("Happy");
ImageIcon happyIcon = new ImageIcon("smiley.gif");
happyButton.setIcon(happyIcon);
 
 
Search WWH ::




Custom Search