Saturday, August 24, 2013

JLabel

JLabel is a component class in SWING package. Unlike Label in AWT package, JLabel can be used to display read-only text, image, or both. In default, text displays to the right of the image. However, you can change this default setting by using the setHorizontalTextPosition(int textposition) method. JLabel component can not generate an event.

The followings are constructors, useful fields and methods of the JLabel class:

Constructors of the JLabel class:
-JLabel()
creates an empty jlabel object.
-JLabel(String text)
creates a jlabel object with the text on it.
-JLabel(String text, int horizontalAlignment)
creates a jlabel object with the text and specified the horizontal alignment.
-JLabel(Icon image)
creates a jlabel object to display an image.
-JLabel(Icon image, int horizontalAlignment)
creates a jlabel object to display an image with specified horizontal alignment.
-JLabel(String text, Icon image, int horizontalAlignment)
creates a jlabel object to display text and an image with specified horizontal alignment.

Useful fields of the JLabel class:
-BOTTOM
-LEFT
-RIGHT
-CENTER
Useful methods of the JLabel class:
-getIcon():Icon
-getText():String
gets the text on the jlabel object.
-setHorizontalTextPosition(int textPosition):void
defines the horizontal position of the text of the jlabel object relative to the image.
-setIconTextGap(int iconTextGap): void
defines the gap between text and image. In default, the gap is 4 pixels wide.
-setText(String text):void
sets the text of the jlabel object.
-setVerticalTextPosition(int textPosition):void
defines the vertical position of the text of the jlabel object relative to the image.

Example:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

class JLabelShow extends JFrame{
JLabelShow(String title){
setTitle(title);
setSize(400,300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Image img=Toolkit.getDefaultToolkit().getImage("penicon.png");
Container contpane=getContentPane();
contpane.setBackground(Color.WHITE);
JLabel jlbl=new JLabel("JLabel can display both text and iamge.",new ImageIcon(img), JLabel.CENTER);
jlbl.setVerticalTextPosition(JLabel.BOTTOM);
contpane.add(jlbl);
setVisible(true);

}
}

public class JFrameSwing {
public static void main(String[] args){
new JLabelShow("JLabel");
}
}

JLabel Swing

To obtain the icon image to be used as the icon of the JLabel, you can use ImageIcon class that implements the Icon interface. An ImageIcon object can be created in two ways based on its constructors. Its first constructor accepts the Image object as its argument (shown in the example code above) and another accepts the string path of the image file as shown below:

String iconpath="d:/openicon.png";
ImageIcon icon=new ImageIcon(iconpath);

No comments:

Post a Comment