Create a custom JLabel with underlined text in Java
Description
The following code shows how to create a custom JLabel with underlined text.
Example
/*from www .j a v a2 s. com*/
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JLabel;
import java.awt.GridLayout;
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame("Popup JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new UnderlinedLabel("java2s.com"));
frame.setSize(300, 200);
frame.setVisible(true);
}
}
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());
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »