How do I draw underlined text in an AWT Label component?
Created May 7, 2012
For example
[FAQ Manager Note] You may want to also adjust the value returned by getPreferredSize() for the Label so it takes into account the underline.
import java.awt.*;
public class MyLabel extends Label {
public MyLabel(String label) {
super(label);
}
public void paint(Graphics g) {
super.paint(g);
int x = 0;
int y = 0;
int width;
int height;
FontMetrics fm = g.getFontMetrics();
width = fm.stringWidth(getText());
height = fm.getHeight();
if (getAlignment() == Label.LEFT)
x = 0;
else if (getAlignment() == Label.CENTER)
x = getBounds().width / 2 - width / 2;
else if (getAlignment() == Label.RIGHT)
x = getBounds().width - width ;
y = getBounds().height / 2 + height / 2 - 4;
g.drawLine(x, y, x + width, y);
}
public void update(Graphics g) {
paint(g);
}
}