Java Swing How to - Extend JLabel to add underline to text








Question

We would like to know how to extend JLabel to add underline to text.

Answer

import java.awt.Graphics;
import java.awt.Rectangle;
/*  w w  w.j  a va 2 s .  co m*/
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Main {
  public static void main(String[] args) {
    UnderlinedLabel label = new UnderlinedLabel("java2s.com");

    
    JOptionPane.showMessageDialog(null, label);
    
  }
}
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());
  }
}