Java Example Program / Sample Source Code
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Line2D;
public class LineMetricsExample {
public static void main(String[] args) {
Frame frame = new Frame("LineMetricsExample");
frame.setSize(400, 400);
frame.add(new CanvasToDisplay());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class CanvasToDisplay extends Component {
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font plainFont = new Font("Serif", Font.PLAIN, 82);
FontRenderContext fontRenderContext = g2D.getFontRenderContext();
g2D.setFont(plainFont);
String message = "JavaTips.net";
// Draw the baseline.
Line2D baseline = new Line2D.Float(40, 140, 400, 140);
g2D.setPaint(Color.red);
g2D.draw(baseline);
// Draw the ascent.
LineMetrics lineMetrics = plainFont.getLineMetrics(message, fontRenderContext);
Line2D ascent = new Line2D.Float(40, 140 - lineMetrics.getAscent(), 400, 140 - lineMetrics.getAscent());
g2D.draw(ascent);
// Draw the descent.
Line2D descent = new Line2D.Float(40, 140 + lineMetrics.getDescent(), 400, 140 + lineMetrics.getDescent());
g2D.draw(descent);
// Draw the leading.
Line2D leading = new Line2D.Float(40, 140 + lineMetrics.getDescent() + lineMetrics.getLeading(), 400, 140 + lineMetrics.getDescent() + lineMetrics.getLeading());
g2D.draw(leading);
g2D.setPaint(Color.black);
g2D.drawString(message, 40, 140);
}
} |
|
|