[an error occurred while processing this directive]

Layout text along a line using LineMetrics

                         

This section illustrates you how to layout text along a line. For this, class LineMetrics is used which layouts the text along a line. The Font class represents the font. The class FontRenderContext measures the text. The class Line2D provides the straight line. 

To return the bounds of the specified text, the method getStringBounds(text, fontRenderContext) is used. The method getLineMetrics( text, fontRenderContext) returns the LineMetrics object with the text and fontRenderContext. The method getAscent() returns the ascent of the text.

The method setPaint() paints the text specified. The method drawString() draws the text along a line.

 

Here is the code of LineMetricsExample.java

import java.awt.*;
import java.awt.font.*;
import javax.swing.*;
import java.awt.geom.Line2D;

public class LineMetricsExample extends JPanel{
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
  Font font = new Font("Monotype Corsiva", Font.PLAIN, 30);
    g2d.setFont(font);
    String text = "Java is an Object Oriented Programming Language";
    float x = 40, y = 70;

    FontRenderContext fontRenderContext = g2d.getFontRenderContext();
    float width = (float) font.getStringBounds(text, fontRenderContext).getWidth();
    Line2D line1 = new Line2D.Float(x, y, x + width, y);
    g2d.setPaint(Color.blue);
    g2d.draw(line1);

    LineMetrics lineMetrics = font.getLineMetrics(text, fontRenderContext);
    Line2D line2 = new Line2D.Float(x, y - lineMetrics.getAscent(), x + width, y
        - lineMetrics.getAscent());
    g2d.draw(line2);
    g2d.setPaint(Color.black);
    g2d.drawString(text, x, y);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Layout text along a line");
    frame.getContentPane().add(new LineMetricsExample());
    frame.setSize(600200);
    frame.show();
    }
}

Output will be displayed as:

Download Source Code

                         

[an error occurred while processing this directive]