Java Swing Tutorial - JLabel








A JLabel represents a label, i.e. a display area for non-editable text.

A JLabel can display both text and images. It can even render HTML tags so that you can create a JLabel that displays multicolors or multiline text.

The javax.swing.JLabel class has the following constructors.

public JLabel ()
public JLabel (java.lang.String text)
public JLabel (java.lang.String text, int horizontalAlignment)
public JLabel (Icon image)
public JLabel (Icon image, int horizontalAlignment)
public JLabel (Java.lang.String text, Icon icon, int horizontalAlignment)
 

The value of horizontalAlignment is one of the following:

  • SwingConstants.LEFT
  • SwingConstants.CENTER
  • SwingConstants.RIGHT
  • SwingConstants.LEADING
  • SwingConstants.TRAILING

Alignments have an effect only if there's extra space for the layout manager to position the component.

The following code shows some examples of how to create a JLabel.

Create a JLabel from a string

JLabel nameLabel  = new JLabel("Name:");

Display an image ok.gif

JLabel warningImage  = new JLabel(new Icon("C:/images/ok.gif"));

The setText() method sets the text for the JLabel.

A JLabel subclass is used as the default renderer for each of the JList, JComboBox, JTable, and JTree components.

import java.awt.FlowLayout;
/*ww  w  . j a v a2  s.  c om*/
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("Label Demo");
    f.setLayout(new FlowLayout());
    f.setSize(300, 200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("java2s.com");
    f.add(label);
    f.setVisible(true);
  }
}




Mnemonic Key

The setDisplayedMnemonic() method sets a keyboard mnemonic for the JLabel. The keyboard mnemonic character is underlined to give a hint to the user.

The setLabelFor() method accepts a reference to another component and it indicates that this JLabel describes that component.

When the mnemonic key for the JLabel is pressed, the focus is set to the component that was used in the setLabelFor() method.

In the following code, the JLabel has its mnemonic set to the character N. When the user presses Alt + N, the focus will be set to the JTextField.

import java.awt.BorderLayout;
// w  w w  . j  a va  2  s  .  co m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JFrame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField nameTextField = new JTextField();
    JLabel nameLabel = new JLabel("Name:");
    nameLabel.setDisplayedMnemonic('N');
    nameLabel.setLabelFor(nameTextField);

    frame.add(nameLabel, BorderLayout.WEST);
    frame.add(nameTextField, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);
  }
}




Multiline label (HTML)

Multiline label (HTML)

import javax.swing.JFrame;
import javax.swing.JLabel;
/*from   www .j  a v  a  2 s  .c o  m*/
public class Main {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("<html>bold <br> plain</html>");
    frame.add(label);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}

If you pass HTML tags to the setText method on a JLabel, the tags must start with "<html>" and end with "</html>".

Text Alignment

We can control the text alignment in a Swing lable.

The following code sets the alignment for both verical and horizontal to center.

label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);

Full source code

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
//from   w  w w.ja v  a  2s .com
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("Label Demo");
    f.setLayout(new FlowLayout());
    f.setSize(300, 200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("java2s.com");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    label.setPreferredSize(new Dimension(150, 100));
    
    label.setText("Centered");
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setVerticalAlignment(JLabel.CENTER);
    f.add(label);
    f.setVisible(true);
  }
}

We can also set the alignment in the JLabel constructor.

JLabel label = new JLabel("Text Label", JLabel.CENTER);

Label Icon

JLabel can also display icon and provide graphic information to the users.

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/* w w w.j a  va  2  s . c o m*/
public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JLabel Test");

    frame.setSize(300, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ImageIcon imageIcon = new ImageIcon("icon.gif");
    JLabel label = new JLabel(imageIcon);

    frame.add(label);
    frame.setVisible(true);
  }
}

The following code create a JLabel by passing in both text and graphic content. It also sets the alignment.

JLabel label = new JLabel("Mixed", imageIcon, SwingConstants.RIGHT);

Label font

JLabel can change text font. The following code creates a new font from Font constructor and set the created font to a JLabel.

import java.awt.Color;
import java.awt.Font;
//  www .j av a2  s . c o m
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("JLabel Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel("First Name");
    label.setFont(new Font("Courier New", Font.ITALIC, 18));
    label.setForeground(Color.RED);

    frame.add(label);
    frame.pack();
    frame.setVisible(true);
  }
}

JLabel Mnemonic Key

The following code shows how to use a JLabel to display the mnemonic for another component.

JLabel is used to display textual or graphic information to the end users. We can also link the JLabel with another control, for example a text field. The text field's purpose is shown in the nearly label control. Usually the labe is placed to the left or top of the target control.

JLabel Mnemonic Key is shown with an underscore and user can focus the target control by press the Alt key + the Mnemonic letter.

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
//from   w  ww. j a  v a 2s . co m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Label Focus Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    
    JTextField textField = new JTextField();
    label.setLabelFor(textField);
    
    frame.add(label, BorderLayout.WEST);
    frame.add(textField, BorderLayout.CENTER);

    frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}

Disable JLabel

import java.awt.FlowLayout;
//from  ww  w.  j a  v a 2  s.co m
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("Label Demo");
    f.setLayout(new FlowLayout());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label= new JLabel("java2s.com");
    label.setEnabled(false);

    f.add(label);
    f.pack();
    f.setVisible(true);
  }
}

JLabel Unicode

import java.awt.GridLayout;
//from ww w  .j av  a 2 s.com
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String args[]) {
    UnicodeJFrame unicodeJFrame = new UnicodeJFrame();
    unicodeJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    unicodeJFrame.setSize(350, 250);
    unicodeJFrame.setVisible(true);
  } 
}

class UnicodeJFrame extends JFrame {
  public UnicodeJFrame() {
    super("Demonstrating Unicode");

    setLayout(new GridLayout(8, 1));

    JLabel englishJLabel = new JLabel("\u0057\u0065\u006C\u0063"
        + "\u006F\u006D\u0065\u0020\u0074\u006F\u0020Unicode\u0021");
    englishJLabel.setToolTipText("This is English");
    add(englishJLabel);

    JLabel chineseJLabel = new JLabel("\u6B22\u8FCE\u4F7F\u7528" + "\u0020\u0020Unicode\u0021");
    chineseJLabel.setToolTipText("This is Traditional Chinese");
    add(chineseJLabel);

    JLabel cyrillicJLabel = new JLabel("\u0414\u043E\u0431\u0440"
        + "\u043E\u0020\u043F\u043E\u0436\u0430\u043B\u043E\u0432"
        + "\u0430\u0422\u044A\u0020\u0432\u0020Unicode\u0021");
    cyrillicJLabel.setToolTipText("This is Russian");
    add(cyrillicJLabel);

    JLabel frenchJLabel = new JLabel("\u0042\u0069\u0065\u006E\u0076"
        + "\u0065\u006E\u0075\u0065\u0020\u0061\u0075\u0020Unicode\u0021");
    frenchJLabel.setToolTipText("This is French");
    add(frenchJLabel);

    JLabel germanJLabel = new JLabel("\u0057\u0069\u006C\u006B\u006F"
        + "\u006D\u006D\u0065\u006E\u0020\u007A\u0075\u0020Unicode\u0021");
    germanJLabel.setToolTipText("This is German");
    add(germanJLabel);

    JLabel japaneseJLabel = new JLabel("Unicode\u3078\u3087\u3045" + "\u3053\u305D\u0021");
    japaneseJLabel.setToolTipText("This is Japanese");
    add(japaneseJLabel);

    JLabel portugueseJLabel = new JLabel("\u0053\u00E9\u006A\u0061"
        + "\u0020\u0042\u0065\u006D\u0076\u0069\u006E\u0064\u006F\u0020" + "Unicode\u0021");
    portugueseJLabel.setToolTipText("This is Portuguese");
    add(portugueseJLabel);

    JLabel spanishJLabel = new JLabel("\u0042\u0069\u0065\u006E"
        + "\u0076\u0065\u006E\u0069\u0064\u0061\u0020\u0061\u0020" + "Unicode\u0021");
    spanishJLabel.setToolTipText("This is Spanish");
    add(spanishJLabel);
  } 
}

JLabel Look and Feel

Customizing a JLabel Look and Feel

Property StringObject Type
Label.actionMapActionMap
Label.backgroundColor
Label.borderBorder
Label.disabledForegroundColor
Label.disabledShadowColor
Label.fontFont
Label.foregroundColor
LabelUIString

JLabel Border

JLabel label= new JLabel("A default label");
Border border = BorderFactory.createLineBorder(Color.BLACK);
label.setBorder(border);

JLabel Drag and Drop

Adding Drag-and-Drop Support to a JLabel Component

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/*w w  w  .j a va 2 s . c o m*/
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.TransferHandler;

public class Main {
  public static void main(String[] argv) throws Exception {
    JLabel label = new JLabel("Label Text");

    final String propertyName = "text";
    label.setTransferHandler(new TransferHandler(propertyName));

    label.addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent evt) {
        JComponent comp = (JComponent) evt.getSource();
        TransferHandler th = comp.getTransferHandler();

        th.exportAsDrag(comp, evt, TransferHandler.COPY);
      }
    });
  }
}

Custom JLabel

Have a Label with underlined text

import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JLabel;

class UnderlinedLabel extends JLabel {
  public UnderlinedLabel() {
    this("");
  }

  public UnderlinedLabel(String text) {
    super(text);
  }

  public void paint(Graphics g) {
    Rectangle r;
    super.paint(g);
    r = g.getClipBounds();
    g.drawLine(0, r.height - getFontMetrics(getFont()).getDescent(), getFontMetrics(getFont())
        .stringWidth(getText()), r.height - getFontMetrics(getFont()).getDescent());
  }
}