Java swing | Java JLabel

Programming languages or concepts
0

 Java JLabel  :

JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both .

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.

By default labels are vertically centered but the user can change the alignment of label.  Label's contents are aligned by setting the vertical and horizontal alignment in its display area.


JLabel class declaration :-

declaration for javax.swing.JLabel class.


public class JLabel extends JComponent implements SwingConstants, Accessible  


Class Declaration :-

declaration for javax.swing.JLabel class −

        public class JLabel

           extends JComponent

          implements SwingConstants, Accessible


Commonly used Constructors:


  Constructor      Description
  JLabel() Creates a JLabel instance with no image and with an empty string for the title.
 JLabel(Icon i)  Creates a JLabel instance with the specified image.
 JLabel(String s)  creates a new label with the string specified.
 JLabel(String s, Icon i, int horizontalAlignment)  Creates a JLabel instance with the specified text, image, and horizontal alignment.


Commonly used Methods | Methods of JLabel class :-


  Constructor      Description
  public void setText(String text) Sets a String message on the JLabel.
 public String getText()  Gets a String message of JLabel.
 public void setIcon(Icon icon)  Sets an icon or image over the JLabel.
 public Icon getIcon()  Gets the icon or image of the JLabel.
 void setHorizontalTextPosition(int textPosition)  Sets the JLabel message on the LEFT/RIGHT of its icon or image.
 void setVerticalTextPosition(int textPosition)  Sets the JLabel message on the TOP/BOTTOM of its icon or image.


Example of JLabel


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JLebel {
    
 public static void main(String... ar)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
new display();
}
});

} //Closing the main method
} //Closing the class Swing1

class display
{
JFrame jf;

JLabel label1, label2, label3;


display()
{
jf = new JFrame("JLabel example");

label1 = new JLabel();
label2 = new JLabel("Hello, Friends");
label3 = new JLabel("Follow this site for improve your programming skill");


label1.setText("Welcome");
jf.setLayout(new FlowLayout());
jf.add(label1);
jf.add(label2);
jf.add(label3);
jf.setVisible(true);
jf.setSize(600,400);
}

Post a Comment

0Comments

Post a Comment (0)
close