Here, str and icon are the text and icon used for the label. The align argument specifies the
horizontal alignment of the text and/or icon within the dimensions of the label. It must be
one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These
constants are defined in the SwingConstants interface, along with several others used by
the Swing classes.
Notice that icons are specified by objects of type Icon, which is an interface defined
by Swing. The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon
implements Icon and encapsulates an image. Thus, an object of type ImageIcon can be
passed as an argument to the Icon parameter of JLabel's constructor. There are several ways
to provide the image, including reading it from a file or downloading it from a URL. Here is
the ImageIcon constructor used by the example in this section:
ImageIcon(String filename)
It obtains the image in the file named filename.
The icon and text associated with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)
void setText(String str)
Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it is possible
to change the text inside a label during program execution.
The following applet illustrates how to create and display a label containing both an
icon and a string. It begins by creating an ImageIcon object for the file france.gif, which
depicts the flag for France. This is used as the second argument to the JLabel constructor.
The first and last arguments for the JLabel constructor are the label text and the alignment.
Finally, the label is added to the content pane.
// Demonstrate JLabel and ImageIcon.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home