What is JLabel - Java Swing

Java examples for Swing:JLabel

Introduction

JLabel is a label used to identify or describe another component.

JLabel can display text, an icon, or both.

Constructors of the JLabel Class

Constructor Description
JLabel() Creates a JLabel with an empty string as its text and no icon.
JLabel(Icon icon) Creates a JLabel with an icon and an empty string as its text.
JLabel(Icon icon, int horizontalAlignment)Creates a JLabel with an icon and the specified horizontal alignment.
JLabel(String text) Creates a JLabel with the specified text.
JLabel(String text, Icon icon, int horizontalAlignment)Creates a JLabel with the specified text, icon, and horizontal alignment.
JLabel(String text, int horizontalAlignment) Creates a JLabel with the specified text and horizontal alignment.

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

Demo Code

import java.awt.BorderLayout;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {

  public Main() {
    super("JButton Clicked Counter");

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    // Create a JLabel with a Name: text
    JLabel nameLabel = new JLabel("Name:");

    // Display an image warning.gif in a JLabel
    JLabel warningImage = new JLabel(new ImageIcon("C:/images/warning.gif"));

    add(nameLabel, BorderLayout.SOUTH);
  }/*  ww w .j  a va2 s .  c  om*/

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials