Java JLabel class example

Beginner java tutorial site is rehosted with updated content and useful information under the domain name javabeginner.com

JLabel

 

    Java Swing Tutorial Explaining the JLabel Component. JLabel, descended from JComponent, is used to create text labels.  A JLabel object provides text instructions or information on a GUI — display a single line of read-only text, an image or both text and image. We use a Swing JLabel when we need a user interface component that displays a message or an image.

JØLabels

  • lProvide text instructions on a GUI
  • lRead-only text
  • lPrograms rarely change a label's contents
  • lClass JLabel (subclass of JComponent)

 

 

JLabel Source Code

Sept 18, 2006 by Hemanth

Swing JLabel API Constructors

 

 
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;

public class JlabelDemo extends JPanel {
    JLabel jlbLabel1, jlbLabel2, jlbLabel3;

    public JlabelDemo() {
    	
        ImageIcon icon = new ImageIcon("java-swing-tutorial.JPG", "My Website");	
	//Creating an Icon 
        
        setLayout(new GridLayout(3,1));
	//3 rows, 1 column Panel having Grid Layout

        jlbLabel1 = new JLabel("Image with Text", icon, JLabel.CENTER);
        
        //We can position of the text, relative to the icon:
        jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM);
        jlbLabel1.setHorizontalTextPosition(JLabel.CENTER);

        jlbLabel2 = new JLabel("Text Only Label");

        jlbLabel3 = new JLabel(icon);		//Label of Icon Only

        //Add labels to the Panel
        add(jlbLabel1);
        add(jlbLabel2);
        add(jlbLabel3);
    }

    public static void main(String[] args) {
     
        JFrame frame = new JFrame("jLabel Usage Demo");

        frame.addWindowListener(new WindowAdapter() {
	//Shows code to Add Window Listener
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        frame.setContentPane(new JlabelDemo());
        frame.pack();
        frame.setVisible(true);
    }
}

 

Output

JLabel
 

		
		

Download jLabel Source Code