Creating an editable JLabel

You can use a CardLayout, assign card 1 a JLabel and assign card 2 a JTextField. Show card 1 and switch to card 2 when it is time to edit. In the following example, the behavior is defined to edit the JLabel whenever the mouse moves over it.

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());
 
      final JLabel label = new JLabel("Move your mouse over this JLabel!");
      final JTextField textfield = new JTextField();
 
      final CardLayout cl = new CardLayout();
      final JPanel panel = new JPanel(cl);
 
      panel.add(label, "label component");
      panel.add(textfield, "textfield component");
 
      getContentPane().add(panel);
  
      label.addMouseListener(new MouseAdapter() {
         public final void mouseEntered(MouseEvent evt) { 
            textfield.setText(label.getText());
            cl.show(panel, "textfield component");
         } 
      });
 
      textfield.addMouseListener(new MouseAdapter() {
         public final void mouseExited(MouseEvent evt) { 
            label.setText(textfield.getText());
            cl.show(panel, "label component");
         } 
      }); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JLabel with strike-through text

The easiest way is to use the HTML tag strike.

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());
 
      JLabel label = new JLabel("<html><strike>Strike-through text</strike></html>");
      getContentPane().add(label);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JLabel with the text underlined

The easiest way is to use the HTML tag u. If you don’t want to use the HTML feature, check out How do I create an underlined JLabel without using HTML?

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());
 
      JLabel label = new JLabel("<html><u>Underlined text with HTML</u></html>");
      getContentPane().add(label);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Changing the background of a JLabel

Call the method setBackground on your component but don’t forget to set your component to be opaque. A component that is not opaque (default) lets whatever is behind them show through. Their backgrounds are determined by the component that is shown behind them.

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("Colored label");
      label.setOpaque(true);
      label.setBackground(Color.white);
 
      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();
   }
}

Creating a vertical JLabel

Code currently works only for 90 or -90 degrees only. It was written to support the answer to the question “How do I create vertically oriented JTable headers”.

Main.java:

import javax.swing.plaf.basic.*;
import javax.swing.border.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      JLabel normalLabel = new JLabel(&quot;Normal JLabel&quot;);
      normalLabel.setBorder(LineBorder.createBlackLineBorder());
 
      JLabel verticalLabel1 = new JLabel(&quot;Vertical JLabel, 90 degrees&quot;);
      verticalLabel1.setUI(new VerticalLabelUI(90));
      verticalLabel1.setBorder(LineBorder.createBlackLineBorder());
 
      JLabel verticalLabel2 = new JLabel(&quot;Vertical JLabel, -90 degrees&quot;);
      verticalLabel2.setUI(new VerticalLabelUI(-90));
      verticalLabel2.setBorder(LineBorder.createBlackLineBorder());
 
      getContentPane().add(normalLabel);
      getContentPane().add(verticalLabel1);
      getContentPane().add(verticalLabel2);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
class VerticalLabelUI extends BasicLabelUI
{
   protected float degrees;
   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);
 
   VerticalLabelUI(float degrees) {
      this.degrees = degrees;
   }
 
   public Dimension getPreferredSize(JComponent c) {
      Dimension dim = super.getPreferredSize(c);
      return new Dimension( dim.height, dim.width );
   }
 
   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) &amp;&amp; (text == null)) {
         return;
      }
 
      FontMetrics fm = g.getFontMetrics();
      paintViewInsets = c.getInsets(paintViewInsets);
 
      paintViewR.x = paintViewInsets.left;
      paintViewR.y = paintViewInsets.top;    	
      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 g2d = (Graphics2D) g;
      // save old value
      AffineTransform affineTransformOld = g2d.getTransform();
 
      double radians = degrees * (Math.PI / 180); 
      g2d.rotate(radians);
      Dimension d = getPreferredSize(c);      
      if (degrees == 90) {
         g2d.translate(0,-d.width);
      } 
      else {
         g2d.translate(-d.height, 0);
      }
 
      if (icon != null) {
         icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
      }
 
      if (text != null) {
         View v = (View) c.getClientProperty(BasicHTML.propertyKey);
         if (v != null) {
            v.paint(g, paintTextR);
         }
         else {
            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);
            }
         }
      } 	
    	
      g2d.setTransform(affineTransformOld);
   }
}

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(&quot;JLabel/icon/LEFT&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEFT));
      panel1.add(new JLabel(&quot;JLabel/icon/CENTER&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.CENTER));
      panel1.add(new JLabel(&quot;JLabel/icon/RIGHT&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.RIGHT));
      panel1.add(new JLabel(&quot;JLabel/icon/LEADING&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEADING));
      panel1.add(new JLabel(&quot;JLabel/icon/TRAILING&quot;, 
                           new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.TRAILING));
 
      getContentPane().add(new JScrollPane(panel1));
 
      JPanel panel2 = new JPanel();
      panel2.setLayout(new GridLayout(5, 1));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/LEFT&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEFT));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/CENTER&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.CENTER));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/RIGHT&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.RIGHT));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/LEADING&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), SwingConstants.LEADING));
      panel2.add(new UnderlinedJLabel(&quot;JLabel/icon/TRAILING&quot;, 
                                      new ImageIcon(&quot;tiffIcon.gif&quot;), 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(&quot;Button.textIconGap&quot;)).intValue());
 
      // draw line
      int textShiftOffset = ((Integer) UIManager.get(&quot;Button.textShiftOffset&quot;)).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);
   }
}