We can use an icon (including Jbutton,jcheckbox,jradiobutton and different types of jmenuitem) in a jlable or anything inherited from AbstractButton. Using the Jlables icon is very easy (we'll see it in a subsequent program example). The following program example explores all the other ways that we can take advantage of button icons and their derivatives.
We can use any GIF file we need, but the GIF file used in this example is part of the book's coded release and can be downloaded at www.BruceEckel.com. To open a file and the resulting image, simply create an icon and assign it a filename. From then on, we can use this generated icon in the program.
: Faces.java//Icon behavior in jbuttons package c13.swing;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*; public class Faces extends JPanel {static icon[] Faces = {new ImageIcon ("Face0.gif"), New ImageIcon ("Face1.gif
"), New ImageIcon (" Face2.gif "), New ImageIcon (" Face3.gif "), New ImageIcon (" Face4.gif "),};
JButton JB = new JButton ("JButton", faces[3)), jb2 = new JButton ("Disable");
Boolean mad = false;
Public Faces () {Jb.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {
if (MAD) {Jb.seticon (faces[3]);
Mad = false;
else {Jb.seticon (faces[0]);
Mad = true;
} jb.setverticalalignment (Jbutton.top);
Jb.sethorizontalalignment (Jbutton.left);
}
});
Jb.setrolloverenabled (TRUE);
Jb.setrollovericon (Faces[1]);
Jb.setpressedicon (faces[2]);
Jb.setdisabledicon (Faces[4]); Jb.settooltIptext ("yow!");
Add (JB); Jb2.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {if (jb.isenabled ())
{jb.setenabled (false);
Jb2.settext ("Enable");
else {jb.setenabled (true);
Jb2.settext ("Disable");
}
}
});
Add (JB2);
public static void Main (String args[]) {show.inframe (New Faces (), 300, 200); }
} ///:~
An icon can be used in many builders, but we can use the SetIcon () method to add or replace icons. This example also shows why it is possible to set various display icons when an event occurs on JButton (or some AbstractButton): When JButton is pressed, when it is invalidated, or when it is "rolled over" (the mouse moves over it but does not hit it). We'll notice that it gives the button a sense of animation.
Note that the ToolTip bar is also added to the button.