Draw underlined text by drawing text and line separately in Java
Description
The following code shows how to draw underlined text by drawing text and line separately.
Example
import java.awt.Font;
import java.awt.Graphics;
// w w w .j av a 2s . c o m
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
String s = "java2s.com";
int x = 10;
int y = 200;
Font font = new Font("Georgia", Font.ITALIC, 50);
g.setFont(font);
g.drawString(s, x, y);
g.drawLine(x, y + 2, x + getFontMetrics(g.getFont()).stringWidth(s), y + 2);
}
}
public class Main {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 450, 450);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
The code above generates the following result.