JLabels - Displays an image and a string in a JLabel on a JFrame

Home  »  Java  »  Advance Java »  »  Swing »  JLabel

Labels are implemented in Swing with JLabel class. The functionality is comparable to AWT labels. In addition to this, icon can be included.

The alignment of a label can be specified with one of three class variables from the SwingConstants class: LEFT, CENTER, OR RIGHT.

To create a label, one of the following constructors can be used:

  1. JLabel(String int) Creates a label with the specified text and alignment.
  2. JLabel(String, Icon int) Creates a label with specified text, icon, and the alignment of text.


The following table describes some of the methods provided by the JLabel class

MethodsDescription
void setHorizontalAlignment(int)
void setVerticalAlignment(int)
int getHorizontalAlignment()
int getVerticalAlignment()

The set of get specifies where in the label its contents should be placed. The SwingConstantsinterface defines five possible values for horizontal alignment: LEFt (the default for text-only labels), CENTER (the default for image-only labels), RIGHT, LEADING, and TRAILING.
For vertical alignment: TOP, CENTER (the default), and BOTTOM.

void setIconTextGap(int)
int getIconTextGap()

Sets or gets the number of pixels between the label's text and its image.

icon getIcon()
void setIcon(Icon)

The getIcon() method returns an icon associated with the image.
The setIcon() method sets an icon to the label.

String getText()
void setText(String)

Returns the text string that the label displays Defines a single line of text the label will display.

void setDisplayedKeyAccelerator(char)
char getDisplayedKeyAccelerator()

The set method specifies a character that indicates the shortcut key.
The get method returns the char that indicates the shortcut key.



The following displays an image and a string in a Label on a Frame.



C:\>jdk1.4\bin>javac DispLblIcon.java
C:\>jdk1.4\bin>appletviwer DispLblIcon.java


"Output of DispLblIcon.class"


Download Complete Program

  -    --  Image



Java Swing-1


JFrame JPanel JApplet
JButtons JLabels JTextFields
JPasswordField JTextAreas JCheckBoxes
JRadioButtons JList JComboBox




No comments:

Post a Comment