How to create and use JLabel
In java, labels are components used to hold the texts. A Label will look like "Text engraved in the container(may be a frame or panel)".
In general what is meant by a Label?
A Label is a piece of a paper that provides information about the object to which it is affixed with. Similarly, here also the sole purpose of a label is to provide information about the object that cannot able to identify itself to the user.
Say, for an example, In java,On seeing a button we can able to tell what it is intended to do, like NEXT, CANCEL, but a text field , text area cannot be able to describe themselves. So, in these kind of situations labels helps us to identify them.
Creating a Label
In order to create a label,we need to create an object for the JLabel class by giving the text to be displayed as a label, like
JLabel l1=new JLabel("NAME");
JLabel l2=new JLabel(ADDRESS);
Program:
LabelDemo.java
import java.util.*;
import javax.swing.*;
import java.awt.*;
class LabelDemo extends JFrame
{
public LabelDemo()
{
setSize(300,300);
setTitle("LabelDemo");
setLayout(new FlowLayout(FlowLayout.CENTER,0,100));
setLocationByPlatform(true);
JPanel p=new JPanel();
JLabel l1=new JLabel("NAME :");
p.add(l1);
JTextField tf=new JTextField(20);
tf.setColumns(10);
p.add(tf);
add(p);
}
}
LabelMain.java
import java.util.*;
import javax.swing.*;
class LabelMain
{
public static void main(String args[])
{
LabelDemo ld=new LabelDemo();
ld.setVisible(true);
ld.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
output:
In java, there is a facility available for us to either add an image , or an image along with the text into a label.Let's see how to add an image into a label.
JLabel l1=new JLabel(new ImageIcon("Nature.jpg"));
JLabel l2=JLabel("Nature",new ImageIcon("Nature.jpg"),SwingConstants.LEFT);
In
tha above example, if you modify the Label creation statement like as
follows it will enable you to add an image to a label.



1 comments:
I liked this article very much. The content is very good. Keep posting.
Visit us: Java Training
Visit us: Java Course
Post a Comment