Explain Basic Swing components JLabel,.
JLabel
The class JLabel can display text, an image, or both. Label's contents are aligned by setting the vertical and horizontal alignment in its display area. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.
Commonly used Constructors of JLabel class are:
JLabel();//Creates label with no text and no image
JLabel(String text); //Create a label with specified text
JLabel(Icon icn); //Creates label with specified icon
JLabel(String text, int allignment); //Creates label with specified text and alignment
JLabel(Icon icn, int allignment); //Creates label with specified icon and alignment
JLabel(String text,Icon icn, int allignment); //Creates label with specified text, icon and alignment
Here alignment can be Label.LEFT or Label.RIGHT or Label.CENTER or Label.TRAILING.
As specified in constructors of JLabel class, we can put image icons in JLabel objects. For this we have to create objects of ImageIcon class by using any one of the following constructors
ImageIcon(String filename);
ImageIcon(String filename, String description);
ImageIcon(Image img);
OR,
JLabel
In Java, Swingtoolkit contains a JLabel Class. It is under package javax.swing.JLabel class. It is used for placing text in a box. Only Single line text is allowed and the text can not be changed directly.
Declaration
public class JLabel extends JComponent implements SwingConstants, Accessible
The JLabel Contains 4 constructors. They are as follows:
1. JLabel()
2. JLabel(String s)
3. JLabel(Icon i)
4. JLabel(String s, Icon i, int horizontalAlignment)
Example
import javax.swing.*;
class SLabelDemo1
{
public static void main(String args[])
{
JFrame label_f= new JFrame("studytonight ==> Label Demo");
JLabel label_l1,label_l2;
label_l1=new JLabel("Welcome to studytonight.com");
label_l1.setBounds(50,50, 200,30);
label_l2=new JLabel("How are You?");
label_l2.setBounds(50,100, 200,30);
label_f.add(label_l1);
label_f.add(label_l2);
label_f.setSize(300,300);
label_f.setLayout(null);
label_f.setVisible(true);
}
}
OR,
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.
JLabel class declaration
Let's see the declaration for java.swing.JLabel class.
public class JLabel extends JComponent implements SwingConstants, Accessible
Java JLabel Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Comments
Post a Comment