Draw font leading,ascent and descent line in Java
Description
The following code shows how to draw font leading,ascent and descent line.
Example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
/*from w w w . ja v a 2 s. co m*/
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
g.setFont (new Font ("TimesRoman", Font.BOLD | Font.ITALIC, 48));
g.translate (2, 100);
FontMetrics fm = null;
int ascent, descent, leading, width1, width2, height;
String string1 = "java2s.com";
String string2 = "Java tutorial";
int xPos = 25, yPos = 50;
fm = g.getFontMetrics();
ascent = fm.getAscent();
descent = fm.getDescent();
leading = fm.getLeading();
height = fm.getHeight();
width1 = fm.stringWidth (string1);
width2 = fm.stringWidth (string2);
g.drawString (string1, xPos, yPos);
g.drawLine (xPos, yPos - ascent - leading,
xPos + width1, yPos - ascent - leading);
g.drawLine (xPos, yPos - ascent,
xPos + width1, yPos - ascent);
g.drawLine (xPos, yPos,
xPos + width1, yPos);
g.drawLine (xPos, yPos + descent,
xPos + width1, yPos + descent);
g.drawString (string2, xPos, yPos+height);
g.drawLine (xPos, yPos - ascent - leading + height,
xPos + width2, yPos - ascent - leading + height);
g.drawLine (xPos, yPos - ascent + height,
xPos + width2, yPos - ascent + height);
g.drawLine (xPos, yPos + height,
xPos + width2, yPos + height);
g.drawLine (xPos, yPos + descent + height,
xPos + width2, yPos + descent + height);
}
}
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.