首页javajlabelJava Swing - 如何扩展JLabel以向文本添加下划线

Java Swing - 如何扩展JLabel以向文本添加下划线

我们想知道如何扩展JLabel以向文本添加下划线。
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

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

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