Sunday, 7 April 2019

JLabel in Java | JLabel in Java Swing with Example

JLabel in java:

      The JLabel in java is a  class which can be used to add a text in the container.it displays a single line read-only data which cannot be changed by the user. JLabel class has three constructors. They are:


JLabel():

It is used to create an empty JLabel

JLable(String str):

It is used to create a JLabel with the specified string str.

JLabel(String str, int align):

It is used to create a JLabel with the specified string str and the alignment. The possible value of the parameters are defined in the string constants are JLabel.The values LEFT,RIGHT,CENTER,NORTH,EAST,and WEST and SOUTH.

The possible values are:

SwingConstants.CENTER or JLabel.CENTER-Displays a string in the JLabel with center alignment.

SwingConstants.LEFT or JLabel.LEFT-Displays a string in the JLabel with the left alignment.

SwingConstants.RIGHT or JLabel.RIGHT-Displays a string in the JLable with right alignment.

Example:

                      JLabel jl1=new JLabel("java",SwingConstants.CENTER);

The above statement is equal to

                      JLabel jl1=new JLabel("java",JLabel.CENTER);

The above example is used to create a JLabel "java" with the center alignment.

Methods:

The most commonly used to JLabel() methods are as follows:

void setText(String str)

The setText() method is used to set the string displayed on the label

void getText()

The getText() method is used to written the current text displayed on the label.

void setIcon(Icon icon)

The setIcon() method is used to specify the icon to display on the label.

void setHorizontalAlignment(int align)

The setHorizontalAlignment() method is used to set the alignment of the label's constants along the x-axis.

void setVerticalAlignment(int align)

The setVerticalAlignment() method is used to set the alignment of the label's constants along the y-axis.

void setFont(Font strFont)

The setFont() method is used to set the font for the JLabel.

void setBackground(Color bgcolor)

The setBackground() method is used to set the color of the background of the JLabel.

void setForeground(Color strcolor)

The setForeground() method is used to set the color of the string for the JLabel.

Sample Program for JLabel in java:

import java.awt.*;
import javax.swing.*;
/*<applet code="JLabeldemo" width=500 height=500></applet>*/
public class JLabelDemo extends JApplet
{
public void intit()
{
Container c= getContentPane();
JLabel jl1=new JLabel("welcome to Online help");
c.setLayout(new FlowLayout());
c.add(jli);
}
}

No comments:

Post a Comment