Java Tutorial/Swing/JLabel — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 04:57, 1 июня 2010

Содержание

Add Icon to JLabel

import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AddingIconJLabel {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame();
    frame.setTitle("JLabel Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ImageIcon imageIcon = new ImageIcon("yourFile.gif");
    JLabel label = new JLabel(imageIcon);
    frame.add(label);
    frame.pack();
    frame.setVisible(true);
  }
}





Adding Drag-and-Drop Support to a JLabel Component

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
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);
      }
    });
  }
}





Add JLabel to JScrollPane

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class ScrollPaneFrame {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    JLabel image = new JLabel(new ImageIcon("A.jpg"));
    frame.getContentPane().add(new JScrollPane(image));
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}





A Label that uses inline HTML to format its text

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends JPanel {
  public static final String markup = "<html>line 1<paragraph><font color=blue size=+2>"
      + "big blue</font> line 2</paragraph>line 3</html>";
  public static void main(String argv[]) {
    JPanel p = new JPanel(new java.awt.GridLayout(0, 1));
    p.add(new JLabel(markup));
    p.add(new java.awt.Label(markup));
    JFrame f = new JFrame("HtmlLabel");
    f.setContentPane(p);
    f.setSize(600, 200);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
}





A label with no indication it has been clicked

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class MyLabel extends JLabel {
  public MyLabel(String msg) {
    super(msg);
    addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent me) {
        fireActionPerformed(new ActionEvent(MyLabel.this, ActionEvent.ACTION_PERFORMED,
            "SecretMessage"));
      }
    });
  }
  public void addActionListener(ActionListener l) {
    listenerList.add(ActionListener.class, l);
  }
  public void removeActionListener(ActionListener l) {
    listenerList.remove(ActionListener.class, l);
  }
  protected void fireActionPerformed(ActionEvent ae) {
    Object[] listeners = listenerList.getListeners(ActionListener.class);
    for (int i = 0; i < listeners.length; i++) {
      ((ActionListener) listeners[i]).actionPerformed(ae);
    }
  }
}





A simple Bean which extends JLabel

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import javax.swing.JLabel;
public class Colors extends JLabel implements Serializable {
  transient private Color color; // not persistent
  private boolean rectangular; // is persistent
  public Colors() {
    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent me) {
        change();
      }
    });
    rectangular = false;
    setSize(200, 100);
    change();
  }
  public boolean getRectangular() {
    return rectangular;
  }
  public void setRectangular(boolean flag) {
    this.rectangular = flag;
    repaint();
  }
  public void change() {
    color = randomColor();
    repaint();
  }
  private Color randomColor() {
    int r = (int) (255 * Math.random());
    int g = (int) (255 * Math.random());
    int b = (int) (255 * Math.random());
    return new Color(r, g, b);
  }
  public void paint(Graphics g) {
    Dimension d = getSize();
    int h = d.height;
    int w = d.width;
    g.setColor(color);
    if (rectangular) {
      g.fillRect(0, 0, w - 1, h - 1);
    } else {
      g.fillOval(0, 0, w - 1, h - 1);
    }
  }
}





Associate JLabel component with a JTextField

import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(400, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.LEFT));
    JLabel usernameLabel = new JLabel("Username: ");
    JLabel passwordLabel = new JLabel("Password: ");
    JTextField usernameField = new JTextField(20);
    JPasswordField passwordField = new JPasswordField(20);
    usernameLabel.setDisplayedMnemonic(KeyEvent.VK_U);
    usernameLabel.setLabelFor(usernameField);
    passwordLabel.setDisplayedMnemonic(KeyEvent.VK_P);
    passwordLabel.setLabelFor(passwordField);
    getContentPane().add(usernameLabel);
    getContentPane().add(usernameField);
    getContentPane().add(passwordLabel);
    getContentPane().add(passwordField);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Create a JLabel with an image icon

import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.LEFT));
    Icon icon = new ImageIcon("a.png");
    JLabel label1 = new JLabel("Full Name :", icon, JLabel.LEFT);
    JLabel label2 = new JLabel("Address :", JLabel.LEFT);
    label2.setIcon(new ImageIcon("b.png"));
    getContentPane().add(label1);
    getContentPane().add(label2);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Create JLabel component

import java.awt.FlowLayout;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(150, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    JLabel label1 = new JLabel("Username :", JLabel.RIGHT);
    JLabel label2 = new JLabel("Password :", JLabel.RIGHT);
    JLabel label3 = new JLabel("Confirm Password :", JLabel.RIGHT);
    JLabel label4 = new JLabel("Remember Me!", JLabel.LEFT);
    JLabel label5 = new JLabel("Hello.", JLabel.CENTER);
    label5.setVerticalAlignment(JLabel.TOP);
    label5.setToolTipText("A tool tip with me!");
    getContentPane().add(label1);
    getContentPane().add(label2);
    getContentPane().add(label3);
    getContentPane().add(label4);
    getContentPane().add(label5);
  }
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}





Customizing a JLabel Look and Feel

Property StringObject TypeLabel.actionMapActionMapLabel.backgroundColorLabel.borderBorderLabel.disabledForegroundColorLabel.disabledShadowColorLabel.fontFontLabel.foregroundColorLabelUIString


Disable a label

import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("asdf");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    label.setEnabled(false);
    f.add(label);
    f.setVisible(true);
  }
}





Gradient Label

/*
 *  soapUI, copyright (C) 2004-2009 eviware.ru 
 *
 *  soapUI is free software; you can redistribute it and/or modify it under the 
 *  terms of version 2.1 of the GNU Lesser General Public License as published by 
 *  the Free Software Foundation.
 *
 *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU Lesser General Public License for more details at gnu.org.
 */

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import javax.swing.JLabel;
public class GradientLabel extends JLabel
{
  // ------------------------------ FIELDS ------------------------------
  private Color start;
  private Color end;
  // --------------------------- CONSTRUCTORS ---------------------------
  public GradientLabel( String text )
  {
    super( text );
    start = Color.LIGHT_GRAY;
    end = getBackground();
  }
  public GradientLabel( String text, Color start, Color end )
  {
    super( text );
    this.start = start;
    this.end = end;
  }
  // -------------------------- OTHER METHODS --------------------------
  public void paint( Graphics g )
  {
    int width = getWidth();
    int height = getHeight();
    // Create the gradient paint
    GradientPaint paint = new GradientPaint( 0, 0, start, width, height, end, true );
    // we need to cast to Graphics2D for this operation
    Graphics2D g2d = ( Graphics2D )g;
    // save the old paint
    Paint oldPaint = g2d.getPaint();
    // set the paint to use for this operation
    g2d.setPaint( paint );
    // fill the background using the paint
    g2d.fillRect( 0, 0, width, height );
    // restore the original paint
    g2d.setPaint( oldPaint );
    super.paint( g );
  }
}





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());
  }
}





Horizontal Alignment: CENTER

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("asdf");
    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);
  }
}





Horizontal Alignment: LEFT

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("asdf");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    label.setPreferredSize(new Dimension(150, 100));
    
    label.setText("Top Left");
    label.setHorizontalAlignment(JLabel.LEFT);
    label.setVerticalAlignment(JLabel.TOP);
    
    f.add(label);
    f.setVisible(true);
  }
}





Horizontal Alignment: RIGHT

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("asdf");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    label.setPreferredSize(new Dimension(150, 100));
    
    label.setText("Bottom Right");
    label.setHorizontalAlignment(JLabel.RIGHT);
    label.setVerticalAlignment(JLabel.BOTTOM);
    
    f.add(label);
    f.setVisible(true);
  }
}





Hyperlink Label

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
public class JHyperlinkLabel extends JLabel {
  private Color underlineColor = null;
  public JHyperlinkLabel(String label) {
    super(label);
    setForeground(Color.BLUE.darker());
    setCursor(new Cursor(Cursor.HAND_CURSOR));
    addMouseListener(new HyperlinkLabelMouseAdapter());
  }
  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(underlineColor == null ? getForeground() : underlineColor);
    Insets insets = getInsets();
    int left = insets.left;
    if (getIcon() != null)
      left += getIcon().getIconWidth() + getIconTextGap();
    g.drawLine(left, getHeight() - 1 - insets.bottom, (int) getPreferredSize().getWidth()
        - insets.right, getHeight() - 1 - insets.bottom);
  }
  public class HyperlinkLabelMouseAdapter extends MouseAdapter {
    @Override
    public void mouseClicked(MouseEvent e) {
      System.out.println(getText());
    }
  }
  public Color getUnderlineColor() {
    return underlineColor;
  }
  public void setUnderlineColor(Color underlineColor) {
    this.underlineColor = underlineColor;
  }
}





JLabel

  1. A JLabel represents a label, i.e. a display area for non-editable text.
  2. A JLabel can display both text and images.
  3. 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:

  1. SwingConstants.LEFT
  2. SwingConstants.CENTER
  3. SwingConstants.RIGHT
  4. SwingConstants.LEADING
  5. SwingConstants.TRAILING

If you want to use multifonts or multicolors in a JLabel, you can pass HTML tags,

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

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


JLabel is for displaying text, images or both. It does not react to input events.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyLabel extends JFrame {
  public static void main(String[] args) {
    String lyrics = "<html>Line<br>line<br>line</html>";
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout(10, 10));
    JLabel label = new JLabel(lyrics);
    label.setFont(new Font("Georgia", Font.PLAIN, 14));
    label.setForeground(new Color(50, 50, 25));
    panel.add(label, BorderLayout.CENTER);
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    JFrame f = new JFrame();
    f.add(panel);
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
}





JLabel with lined border

import java.awt.Color;
import java.awt.FlowLayout;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("A default label");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    f.add(label);
    f.setVisible(true);
  }
}





JLabel with more than one row

JLabel label = new JLabel();
label.setText("<html>Line 1<br>Line 2</html>");





Load image from disk file and add it to a JLabel

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class AddingIconToJLabel {
  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Icon icon = new ImageIcon("yourFile.gif");
    JLabel label3 = new JLabel("Warning", icon, JLabel.CENTER);
    frame.add(label3);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}





Mix Icon and text in JLabel

import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class MixingIconLabel {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame();
    frame.setTitle("JLabel Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ImageIcon imageIcon = new ImageIcon("yourFile.gif");
    JLabel label = new JLabel("Mixed", imageIcon, SwingConstants.RIGHT);
    frame.add(label);
    frame.pack();
    frame.setVisible(true);
  }
}





Multi Line Label

/*
 This file is part of the BlueJ program. 
 Copyright (C) 1999-2009  Michael K�lling and John Rosenberg 
 
 This program is free software; you can redistribute it and/or 
 modify it under the terms of the GNU General Public License 
 as published by the Free Software Foundation; either version 2 
 of the License, or (at your option) any later version. 
 
 This program is distributed in the hope that it will be useful, 
 but WITHOUT ANY WARRANTY; without even the implied warranty of 
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 GNU General Public License for more details. 
 
 You should have received a copy of the GNU General Public License 
 along with this program; if not, write to the Free Software 
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. 
 
 This file is subject to the Classpath exception as provided in the  
 LICENSE.txt file that accompanied this code.
 */
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
 ** @version $Id: MultiLineLabel.java 6164 2009-02-19 18:11:32Z polle $
 ** @author Justin Tan
 ** A multi-line Label-like AWT component.
 **/
public class MultiLineLabel extends JPanel
{
    protected int fontAttributes = Font.PLAIN;
    protected float alignment;
    protected Color col = null;
  protected int spacing = 0;
    
    /**
     ** Constructor - make a multiline label
     **/
    public MultiLineLabel(String text, float alignment)
    {
        this.alignment = alignment;
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        if(text != null)
            setText(text);
    }
    /**
     ** Constructor, defaults to centered text
     **/
    public MultiLineLabel(String text)
    {
        this(text, LEFT_ALIGNMENT);
    }
    /**
     * Constructor, empty with the given alignment
     */
    public MultiLineLabel(float alignment)
    {
        this(null, alignment);
    }
    /**
     * Constructor, empty with the given alignment and line spacing
     */
    public MultiLineLabel(float alignment, int spacing)
    {
        this(null, alignment);
        this.spacing = spacing;
    }
    /**
     ** Constructor - make an empty multiline label
     **/
    public MultiLineLabel()
    {
        this(null, LEFT_ALIGNMENT);
    }
  
    public void setText(String text)
    {
        // clear the existing lines from the panel
        removeAll();
        addText(text);
    }
  
    public void addText(String text)
    {
        addText(text, 12);
    }
    
    public void addText(String text, int size)
    {
        if(spacing > 0)
            add(Box.createVerticalStrut(spacing));
        String strs[] = splitLines(text);
        JLabel l;
        Font font = new Font("SansSerif", fontAttributes, size);
        for (int i = 0; strs != null && i < strs.length; i++) {
            l = new JLabel(strs[i]);
            l.setFont(font);
            l.setAlignmentX(alignment);
            if (col != null)
                l.setForeground(col);
            add(l);
        }   
    }
    /**
     * Splits "string" by "Delimiter"
     * 
     * @param str - the string to be split
     * @param delimiter - the field delimiter within str
     * @returns an array of Strings
     */
    public static String[] split(String str, String delimiter)
    {
        List<String> strings = new ArrayList<String>();
        int start = 0;
        int len = str.length();
        int dlen = delimiter.length();
        int offset = str.lastIndexOf(delimiter); // First of all, find the
        // Last occurance of the Delimiter
        // Stop empty delimiters
        if (dlen < 1)
            return null;
        else if (offset < 0) // one element
        {
            String[] result = {str};
            return result;
        }
        //
        // Append the delimiter onto the end if it doesn"t already exit
        //
        if (len > offset + dlen) {
            str += delimiter;
            len += dlen;
        }
        do {
            // Get the new Offset
            offset = str.indexOf(delimiter, start);
            strings.add(str.substring(start, offset));
            // Get the new Start position
            start = offset + dlen;
        } while ((start < len) && (offset != -1));
        // Convert the list into an Array of Strings
        String result[] = new String[strings.size()];
        strings.toArray(result);
        return result;
    }
    /**
     * Splits "string" into lines (stripping end-of-line characters)
     * 
     * @param str - the string to be split
     * @returns an array of Strings
     */
    public static String[] splitLines(String str)
    {
        return (str == null ? null : split(str, "\n"));
    }
    public void addText(String text, boolean bold, boolean italic)
    {
        int oldAttributes = fontAttributes;
        setBold(bold);
        setItalic(italic);
        addText(text);
        fontAttributes = oldAttributes;
    }
    public void setForeground(Color col)
    {
        this.col = col;    
        Component[] components = this.getComponents();
        for (int i = 0; i < components.length; i++) {
      Component component = components[i];
      component.setForeground(col);
    }
    }
      
    public void setItalic(boolean italic)
    {
        if(italic)
           fontAttributes |= Font.ITALIC;
        else
            fontAttributes &= ~Font.ITALIC;
    }
  
    public void setBold(boolean bold)
    {
        if(bold)
            fontAttributes |= Font.BOLD;
        else
            fontAttributes &= ~Font.BOLD;
    }
}





Multiline label (HTML)

import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("<html>Use HTML to create<br>" + "a multiline message."
        + "<br>One<br>Two<br>Three");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    f.add(label);
    f.setVisible(true);
  }
}





Set Font and foreground color for a JLabel

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JLabelFontForeground {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame();
    frame.setTitle("JLabel Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel("First Name");
    label.setFont(new Font("Courier New", Font.ITALIC, 12));
    label.setForeground(Color.GRAY);
    frame.add(label);
    frame.pack();
    frame.setVisible(true);
  }
}





Setting the Focus of a JTextField Component Using a JLabel Component

import java.awt.event.KeyEvent;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField textfield = new JTextField(25);
    // Create label and associate with text field
    JLabel label = new JLabel("Text Label");
    label.setDisplayedMnemonic(KeyEvent.VK_L);
    label.setLabelFor(textfield);
  }
}





The text is horizontally and vertically centered

import javax.swing.JLabel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JLabel label = new JLabel("Text Label", JLabel.CENTER);
  }
}





The text is left-justified and bottom-aligned

import javax.swing.JLabel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JLabel label = new JLabel("Text Label", JLabel.LEFT);
    label.setVerticalAlignment(JLabel.BOTTOM);
  }
}





The text is left-justified and top-aligned

import javax.swing.JLabel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JLabel label = new JLabel("Text Label", JLabel.LEFT);
    label.setVerticalAlignment(JLabel.TOP);
  }
}





The text is right-justified and bottom-aligned

import javax.swing.JLabel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JLabel label = new JLabel("Text Label", JLabel.RIGHT);
    label.setVerticalAlignment(JLabel.BOTTOM);
  }
}





The text is right-justified and top-aligned

import javax.swing.JLabel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JLabel label = new JLabel("Text Label", JLabel.RIGHT);
    label.setVerticalAlignment(JLabel.TOP);
  }
}





The text is right-justified and vertically centered

import javax.swing.JLabel;
public class Main {
  public static void main(String[] argv) throws Exception {
    JLabel label = new JLabel("Text Label", JLabel.RIGHT);
  }
}





Time panel shows the current time.

/*
 * Copyright (C) 2002-2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Calendar;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.border.Border;
/**
 * Time panel. This will show the current time.
 * A timer to update the time is started when the component
 * is added to its parent and stopped when removed from its parent.
 *
 * @author 
 */
public class TimePanel extends JLabel implements ActionListener
{
  /** Timer that updates time. */
  private Timer _timer;
  /** Used to format the displayed date. */
  private DateFormat _fmt = DateFormat.getTimeInstance(DateFormat.LONG);
  private Dimension _prefSize;
  private Calendar _calendar = Calendar.getInstance();
  /**
   * Default ctor.
   */
  public TimePanel()
  {
    super("", JLabel.CENTER);
  }
  /**
   * Add component to its parent. Start the timer for auto-update.
   */
  public void addNotify()
  {
    super.addNotify();
    _timer = new Timer(1000, this);
    _timer.start();
  }
  /**
   * Remove component from its parent. Stop the timer.
   */
  public void removeNotify()
  {
    super.removeNotify();
    if (_timer != null)
    {
      _timer.stop();
      _timer = null;
    }
  }
  /**
   * Update component with the current time.
   *
   * @param evt   The current event.
   */
  public void actionPerformed(ActionEvent evt)
  {
    _calendar.setTimeInMillis(System.currentTimeMillis());
    setText(_fmt.format(_calendar.getTime()));
  }
  /**
   * Return the preferred size of this component.
   *
   * @return  the preferred size of this component.
   */
  public Dimension getPreferredSize()
  {
    if(null == _prefSize)
    {
      // This was originaly done every time.
      // and the count of instantiated objects was amazing
      _prefSize = new Dimension();
      _prefSize.height = 20;
      FontMetrics fm = getFontMetrics(getFont());
      Calendar cal = Calendar.getInstance();
      cal.set(Calendar.HOUR_OF_DAY, 23);
      cal.set(Calendar.MINUTE, 59);
      cal.set(Calendar.SECOND, 59);
      _prefSize.width = fm.stringWidth(_fmt.format(cal.getTime()));
      Border border = getBorder();
      if (border != null)
      {
        Insets ins = border.getBorderInsets(this);
        if (ins != null)
        {
          _prefSize.width += (ins.left + ins.right);
        }
      }
      Insets ins = getInsets();
      if (ins != null)
      {
        _prefSize.width += (ins.left + ins.right) + 20;
      }
    }
    return _prefSize;
  }
}





Unicode with Label

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Unicode {
  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);
  } 
}





URL Label

//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the 
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003. 
//
//All Rights Reserved.
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.net.URL;
import javax.swing.JLabel;
public class URLLabel extends JLabel {
  boolean entered = false;
  boolean mousehover;
  public URLLabel(URL url) {
    this(url, url.toString());
  }
  public URLLabel(URL url, String str) {
    super(str);
    setForeground(Color.blue);
    mousehover = false;
  }
  public void mouseEntered(MouseEvent e) {
    setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    entered = true;
    if (mousehover) {
      repaint();
    }
  }
  public void mouseExited(MouseEvent e) {
    setCursor(Cursor.getDefaultCursor());
    entered = false;
    if (mousehover) {
      repaint();
    }
  }
  public void mousePressed(MouseEvent e) {
  }
  public void mouseReleased(MouseEvent e) {
  }
  public void paint(Graphics g) {
    super.paint(g);
    if (entered || !mousehover) {
      Rectangle r = g.getClipBounds();
      g.drawLine(0, r.height - this.getFontMetrics(this.getFont()).getDescent(), this
          .getFontMetrics(this.getFont()).stringWidth(this.getText()), r.height
          - this.getFontMetrics(this.getFont()).getDescent());
    }
  }
}





Using a JLabel and pass in HTML for the text

import javax.swing.JFrame;
import javax.swing.JLabel;
public class HTMLLabel {
  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>".


Vertical Alignment: BOTTOM

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("asdf");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    label.setPreferredSize(new Dimension(150, 100));
    
    label.setText("Bottom Right");
    label.setHorizontalAlignment(JLabel.RIGHT);
    label.setVerticalAlignment(JLabel.BOTTOM);
    
    f.add(label);
    f.setVisible(true);
  }
}





Vertical Alignment: CENTER

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("asdf");
    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);
  }
}





Vertical Alignment: TOP

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
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(200, 360);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JLabel label= new JLabel("asdf");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    label.setPreferredSize(new Dimension(150, 100));
    
    label.setText("Top Left");
    label.setHorizontalAlignment(JLabel.LEFT);
    label.setVerticalAlignment(JLabel.TOP);
    
    f.add(label);
    f.setVisible(true);
  }
}





Vertical Label UI

/*
 * The contents of this file are subject to the Sapient Public License
 * Version 1.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://carbon.sf.net/License.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 *
 * The Original Code is The Carbon Component Framework.
 *
 * The Initial Developer of the Original Code is Sapient Corporation
 *
 * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
 */

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.plaf.basic.BasicLabelUI;
/**
 * This is the template for Classes.
 *
 *
 * @since carbon 1.0
 * @author Greg Hinkle, January 2002
 * @version $Revision: 1.4 $($Author: dvoet $ / $Date: 2003/05/05 21:21:27 $)
 * @copyright 2002 Sapient
 */
public class VerticalLabelUI extends BasicLabelUI {
    static {
        labelUI = new VerticalLabelUI(false);
    }
    protected boolean clockwise;

    public VerticalLabelUI(boolean clockwise) {
        super();
        this.clockwise = clockwise;
    }

    public Dimension getPreferredSize(JComponent c) {
        Dimension dim = super.getPreferredSize(c);
        return new Dimension( dim.height, dim.width );
    }
    private static Rectangle paintIconR = new Rectangle();
    private static Rectangle paintTextR = new Rectangle();
    private static Rectangle paintViewR = new Rectangle();
    private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
    public void paint(Graphics g, JComponent c) {
        JLabel label = (JLabel)c;
        String text = label.getText();
        Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
        if ((icon == null) && (text == null)) {
            return;
        }
        FontMetrics fm = g.getFontMetrics();
        paintViewInsets = c.getInsets(paintViewInsets);
        paintViewR.x = paintViewInsets.left;
        paintViewR.y = paintViewInsets.top;
        // Use inverted height & width
        paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
        paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
        paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
        paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
        String clippedText =
            layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
        Graphics2D g2 = (Graphics2D) g;
        AffineTransform tr = g2.getTransform();
        if (clockwise) {
            g2.rotate( Math.PI / 2 );
            g2.translate( 0, - c.getWidth() );
        } else {
            g2.rotate( - Math.PI / 2 );
            g2.translate( - c.getHeight(), 0 );
        }
        if (icon != null) {
            icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
        }
        if (text != null) {
            int textX = paintTextR.x;
            int textY = paintTextR.y + fm.getAscent();
            if (label.isEnabled()) {
                paintEnabledText(label, g, clippedText, textX, textY);
            } else {
                paintDisabledText(label, g, clippedText, textX, textY);
            }
        }
        g2.setTransform( tr );
    }
}