In this tutorial you will learn about the Swing JLabel and its application with practical example.
Swing JLabel
The JLabel Class is used to display a single line of read only text. Read only means user can not change it but it can be changed by an application. The JLabel class extends JComponent class.
A JLabel can display either text, an image, or both.
JLabel Class Declaration
1 |
public class JLabel extends JComponent implements SwingConstant, Accessible. |
JLabel Constructor
Some commonly used constructor listed below.
JLabel(): This constructor is used to create instance of JLabel with no image and empty string value.
Syntax:-
1 |
JLabel jlb=new JLabel(); |
JLabel(Icon Image): This constructor is used to create instance of JLabel with an Image icon.
Syntax:-
1 |
JLabel jlb=new JLabel(icon); |
JLabel(String text): This constructor is used to create instance of JLabel with specific text.
Syntax:-
1 |
JLabel jlb=new JLabel(“Hello”); |
JLabel(String text, Icon image, int horizontalAlignment): This constructor is used to create an instance of JLabel with String ,Image and horizontal alignment.
Syntax:-
1 |
JLabel jlb =new JLabel(“Hello”, icon, 20); |
JLabel Methos
Some of commonly used methods are listed below.
Icon getIcon(): This method is used to return an icon which is displayed to this Label.
String getText() : This method is used to return String of JLabel.
void setText(String text): This method is used to set Text to the JLabel.
void setIcon(Icon icon): This method is used to set icon on the JLabel.
void setHorizontalAlignment(int alignment): This method is used to sets the horizontal position of the Jlabel’s content along the X- axis.
void setVerticalAlignment(int alignment): This method is used to sets the vertical position of the JLabel’s content along the Y-axis.
int getHorizontalAlignment(): This method is used to returns the alignment of the label’s contents along the X-axis and return type is Integer.
Int getVerticalAlignment(): This method is used to returns the alignment of the label’s contents along with the Y-axis and return type is Integer.
Example :-
From the below example we will get understand about JLabel class. This is the simple example you can do more on it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//code:start package w3addaswing; import javax.swing.JFrame; import javax.swing.JLabel; public class W3ADDASwing { public static void main(String[] args) { // TODO code application logic here JFrame frame= new JFrame("Label Example W3ADDA"); JLabel label; label=new JLabel("JLabel of w3adda.com"); label.setBounds(50,50, 130,30); frame.add(label); frame.setSize(400,400); frame.setLayout(null); frame.setVisible(true); } } //Code: End |
Output :-
The output of this code will look like below image.