Drawing an image in a JLabel

Very simple: look at the constructors of JLabel and you’ll see that some of them accept images. A JLabel can contain either text, an image or both. If you have both images and text, you can set the horizontal and vertical text position using the methods:

      setVerticalTextPosition
      setHorizontalTextPosition

Here’s a complete example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JLabel label;
 
   public Main() {
      label = new JLabel("The Logo", new ImageIcon("d:\ESUSLOGO.gif"), 

SwingConstants.CENTER);
      label.setVerticalTextPosition(SwingConstants.BOTTOM);
      label.setHorizontalTextPosition(SwingConstants.CENTER);
      getContentPane().add(BorderLayout.CENTER, label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setSize(300, 200);
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Creating an underlined JLabel without using HTML

Main.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new GridLayout(1, 2));
      JPanel panel1 = new JPanel();
      panel1.setLayout(new GridLayout(5, 1));
      panel1.add(new JLabel("JLabel/icon/LEFT", 
                           new ImageIcon("tiffIcon.gif"), SwingConstants.LEFT));
      panel1.add(new JLabel("JLabel/icon/CENTER", 
                           new ImageIcon("tiffIcon.gif"), SwingConstants.CENTER));
      panel1.add(new JLabel("JLabel/icon/RIGHT", 
                           new ImageIcon("tiffIcon.gif"), SwingConstants.RIGHT));
      panel1.add(new JLabel("JLabel/icon/LEADING", 
                           new ImageIcon("tiffIcon.gif"), SwingConstants.LEADING));
      panel1.add(new JLabel("JLabel/icon/TRAILING", 
                           new ImageIcon("tiffIcon.gif"), SwingConstants.TRAILING));
 
      getContentPane().add(new JScrollPane(panel1));
 
      JPanel panel2 = new JPanel();
      panel2.setLayout(new GridLayout(5, 1));
      panel2.add(new UnderlinedJLabel("JLabel/icon/LEFT", 
                                      new ImageIcon("tiffIcon.gif"), SwingConstants.LEFT));
      panel2.add(new UnderlinedJLabel("JLabel/icon/CENTER", 
                                      new ImageIcon("tiffIcon.gif"), SwingConstants.CENTER));
      panel2.add(new UnderlinedJLabel("JLabel/icon/RIGHT", 
                                      new ImageIcon("tiffIcon.gif"), SwingConstants.RIGHT));
      panel2.add(new UnderlinedJLabel("JLabel/icon/LEADING", 
                                      new ImageIcon("tiffIcon.gif"), SwingConstants.LEADING));
      panel2.add(new UnderlinedJLabel("JLabel/icon/TRAILING", 
                                      new ImageIcon("tiffIcon.gif"), SwingConstants.TRAILING));
 
      getContentPane().add(new JScrollPane(panel2));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);   
   }
}
 
class UnderlinedJLabel extends JLabel
{
   public UnderlinedJLabel() {
   }
 
   public UnderlinedJLabel(Icon image) {
      super(image);
   }
 
   public UnderlinedJLabel(Icon image, int horizontalAlignment) {
      super(image, horizontalAlignment);
   }
 
   public UnderlinedJLabel(String text) {
      super(text);
   }

   public UnderlinedJLabel(String text, Icon icon, int horizontalAlignment) {
      super(text, icon, horizontalAlignment);
   }
 
   public UnderlinedJLabel(String text, int horizontalAlignment) {
      super(text, horizontalAlignment);
   }
 
   public void paint(Graphics g) {
      super.paint(g);
      underline(g);
   }
 
   protected void underline(Graphics g) {
      Insets insets = getInsets();
      FontMetrics fm = g.getFontMetrics();
      Rectangle textR = new Rectangle();
      Rectangle viewR = new Rectangle(
                                  insets.left, 
                                  insets.top, 
                                  getWidth() - (insets.right + insets.left), 
                                  getHeight() - (insets.bottom + insets.top));
  
      // compute and return location of the icons origin,
      // the location of the text baseline, and a possibly clipped
      // version of the compound label string.  Locations are computed 
      // relative to the viewR rectangle.
      String text = SwingUtilities.layoutCompoundLabel(
                         this,                        // this JLabel
                         fm,                          // current FontMetrics
                         getText(),                   // text
                         getIcon(),                   // icon
                         getVerticalAlignment(),      
                         getHorizontalAlignment(),
                         getVerticalTextPosition(),
                         getHorizontalTextPosition(), 
                         viewR,                       
                         new Rectangle(),             // don't care about icon rectangle
                         textR,                       // resulting text locations
                         getText() == null ? 0 : 
                            ((Integer)UIManager.get("Button.textIconGap")).intValue());
 
      // draw line
      int textShiftOffset = ((Integer) UIManager.get("Button.textShiftOffset")).intValue();
      g.fillRect(textR.x +
                 textShiftOffset - 4,
                 textR.y + fm.getAscent() + textShiftOffset + 2,
                 textR.width, 
                 1);
   }
}

Creating a multi-colored JLabel

A couple of ways to do this. The easiest being that you can use HTML in labels and hence add the font tag inside your text (see example). Another way is to create a custom extended JLabel component that exposes some methods to set the color of individual characters or ranges or characters and create a custom JLabel UI that takes this extra information to render the JLabel correctly.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("<html><font color=blue>Colored</font> <font color=yellow>label</font></html>");
 
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 100);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Showing the copyright symbol in a JLabel

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JLabel label = new JLabel("Copyrightu00a9, All rights reserved");
      getContentPane().add(label);
 
      label.putClientProperty("html", null);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JLabel with the icon on top and text below

Here’s a complete example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JLabel label;
 
   public Main() {
      label = new JLabel("The Logo", new ImageIcon("d:\ESUSLOGO.gif"), 

SwingConstants.CENTER);
      label.setVerticalTextPosition(SwingConstants.BOTTOM);
      label.setHorizontalTextPosition(SwingConstants.CENTER);
      getContentPane().add(BorderLayout.CENTER, label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setSize(300, 200);
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Showing the trademark symbol in a JLabel

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JLabel label = new JLabel("Javau2122");
      getContentPane().add(label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JLabel with the text on top of the image

You can play around with the methods setHorizontalTextAlignment and setVerticalTextAlignment as shown in the following example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("esus.com", new ImageIcon("esuslogo.gif"), JLabel.CENTER);
      label.setHorizontalTextPosition(JLabel.CENTER); 
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a multi-line text JLabel

The easiest way is to hardcode HTML inside your JLabel text. JLabel has the functionality to render HTML. Another way is to write a custom Jlabel UI for your l&f that is able to understand escape sequences like n.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("<html>Java resources at<br>esus.com<html>");
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a multi-line text tooltip for a JLabel

An easy way is to have your tooltip text to be HTML:

   label.setToolTipText("<html>This is a two-line<br> tooltip text!</html>");

as in following example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
                            
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      JLabel label = new JLabel("Mouse-over me!");
      getContentPane().add(label);
                         
      label.setToolTipText("<html>This is a two-line<br> tooltip text!</html>");
                         
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
                           
      setSize(new Dimension(200, 200));
   } 
                         
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}

Embedding a clickable HTML image in a JLabel

A JLabel is able to render HTML but it does not respond to clicks on anchor tags. You could do something simple like add a MouseListener to your JLabel and respond to mouse events like a normal browser would.

Main.java:

import java.awt.event.*;
import java.awt.font.*; 
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JLabel label = new JLabel("<html><a href="dummy"><img src="file:c:\esuslogo.gif"></a></html>");
      getContentPane().add(label);
 
      label.addMouseListener(new MouseAdapter() {
         public void mouseEntered(MouseEvent me) {
            label.setCursor(new Cursor(Cursor.HAND_CURSOR));
         }
         public void mouseExited(MouseEvent me) {
            label.setCursor(Cursor.getDefaultCursor());
         }
         public void mouseClicked(MouseEvent me) {
            System.out.println("Clicked on JLabel image");
         }
      });
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}