How do I draw underlined text in an AWT Label component?

Erdem Gunay

You can create your own Label class extending original java.awt.Label class and override the paint method.

For example


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

[FAQ Manager Note] You may want to also adjust the value returned by getPreferredSize() for the Label so it takes into account the underline.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact