by Dinesh Thakur Category: Swing

JLabel component in swing is similar to label in AWT except that it may contain uneditable text, an image or both. We can create label by creating an instance of JLabel class.

 

JLabel (label) does not react to user events so you can not get the keyboard focus. It often used in combination with other components which do not have the ability to demonstrate its purpose, for example, in combination with a JTextField serve us to tell the user what we expect to enter into it.

The following table shows some methods of this class:

 

Method  

Description

JLabel()                 

Constructs a label with no text

JLabel(String)     

Constructs a label with the text entered

JLabel(Icon)       

Constructs a label containing the specified image

setText(String)    

Sets the text to be shown

The JLabel class defines several methods to change the appearance of the component:

Method

Description

setText()

To initializeorchange the text displayed

setOpaque()

Indicates whether the component is transparent (false parameter) or opaque (true)

setBackground()

Specifies the background color of the component (setOpaque must be true)

setFont()

Specifiesthe text font

setForeGround()

Specifiesthe text color

setHorizontalAlignment()

Allows you to change the horizontal alignment of text and icon

setVerticalAlignment()

Allows you to change the vertical alignment of text and icon

setHorizontalTextAlignment()

Allows you to change the horizontal alignment of text only

setVerticalTextAlignment()

Allows you to change the vertical alignment of text only

setIcon()

Allows you to assign an icon

setDisabledIcon()

Sets the icon for the JLabel when disabled

 

import javax.swing.*;

import java.awt.*;
class JLabelExample extends JFrame
{
    JLabelExample()
    { 
         setLayout(new FlowLayout());
         ImageIcon icon = new ImageIcon("Check.png");
         JLabel lblText = new JLabel("Label with Text");
         JLabel lblTextIcon = new JLabel("Text and icon",icon, SwingConstants.RIGHT);
         add(lblText);
         add(lblTextIcon);
     }
}
 class JLabelSwingExample
{
       public static void main(String args[])
      {
            JLabelExample frame = new JLabelExample();
            frame.setTitle("JLabel in Java Swing Example");
            frame.setBounds(200,250,150,150);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
      }
}

JLabel in Java Swing Example



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article