JLabel Border and Image Example

Swing Label can be set with borders and images which is not possible with AWT Label component. Alignment is also possible.

Following code explains.

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

public class JLabelDemo2 extends JFrame
  public JLabelDemo2()
    Container c = getContentPane();
    c.setLayout(new GridLayout(3, 1, 0, 10)); 
						// ordinary text like Label of AWT		
    JLabel lab1 = new JLabel("Ordianry Test");
                                                // text with border		
    JLabel lab2 = new JLabel("This is Ordianry Test but bordered");
    lab2.setBorder(BorderFactory.createTitledBorder("Bordered Text"));
                                                // a text with image and border
    JLabel lab3 = new JLabel("Birds give life to Nataure", new ImageIcon("bird3.gif"), SwingConstants.RIGHT);
					        // by default image is left and text is right but is changed in the above statement and the image comes right and text left

    setTitle("Mixed Momentum");
  public static void main(String args[])
    new JLabelDemo2( );


There are three labels in the above output screen, lab1, lab2 and lab3.

JLabel lab1 = new JLabel(“Ordianry Test”);

lab1 comes with simple test like our AWT Label. Pass the text to the constructor.

JLabel lab2 = new JLabel(“This is Ordianry Test but bordered”);
lab2.setBorder(BorderFactory.createTitledBorder(“Bordered Text”));

lab2 is set with a border – titled border. It is like you have set earlier with JButton.

JLabel lab3 = new JLabel(“Birds give life to Nataure”, new ImageIcon(“bird3.gif”), SwingConstants.RIGHT);

By default image comes to left and text to right but is changed in the above statement where the image comes right and the text left.

SwingConstants.RIGHT can be changed to SwingConstants.LEFT or SwingConstants.CENTER to align the text to left and center.

Leave a Comment

Your email address will not be published.