Java Reference
In-Depth Information
When you begin working with Swing components, a common
source of mistakes is to set up aspects of a component after it
has been added to a container. Make sure to set up all aspects of
a component before placing it in a panel or any other container.
CAUTION
Image Icons
Swing supports the use of graphical ImageIcon objects on buttons and other components
in which a label can be provided. An icon is a small graphic that can be placed on a but-
ton, label, or other user interface element to identify it—such as a garbage can or recy-
cling bin icon for deleting files, folder icons for opening and storing files, and the like.
9
An ImageIcon object can be created by specifying the filename of a graphic as the only
argument to the constructor. The following example loads an icon from the graphics file
subscribe.gif and creates a JButton with the icon as its label:
ImageIcon subscribe = new ImageIcon(“subscribe.gif”);
JButton button = new JButton(subscribe);
JPanel pane = new JPanel();
pane.add(button);
add(pane);
setVisible(true);
Listing 9.4 contains a Java application that creates four image icons with text labels, adds
them to a panel, and then adds the panel to a frame.
LISTING 9.4
The Full Text of IconFrame.java
1: import javax.swing.*;
2:
3: public class IconFrame extends JFrame {
4: JButton load, save, subscribe, unsubscribe;
5:
6: public IconFrame() {
7: super(“Icon Frame”);
8: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9: JPanel panel = new JPanel();
10: // create icons
11: ImageIcon loadIcon = new ImageIcon(“load.gif”);
12: ImageIcon saveIcon = new ImageIcon(“save.gif”);
13: ImageIcon subscribeIcon = new ImageIcon(“subscribe.gif”);
14: ImageIcon unsubscribeIcon = new ImageIcon(“unsubscribe.gif”);
15: // create buttons
16: load = new JButton(“Load”, loadIcon);
17: save = new JButton(“Save”, saveIcon);
 
Search WWH ::




Custom Search