import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Point2D;
import java.text.AttributedCharacterIterator;

/**
 * This class shows how to construct and draw a TextLayout.
 *
 * This class constructs a TextLayout from an 
 * AttributedCharacterIterator and draws it.
 */
public class DrawSample extends Component {

    // The TextLayout to draw.
    private TextLayout textLayout;

    public DrawSample(AttributedCharacterIterator text) {

        FontRenderContext frc = SampleUtils.getDefaultFontRenderContext();

        // Create a new TextLayout from the given text.
        textLayout = new TextLayout(text, frc);
    }

    /**
     * Compute a location within this Component for textLayout's origin,
     * such that textLayout is centered horizontally and vertically.
     * Note that this location is unknown to textLayout;  it is used only
     * by this Component for positioning.
     */
    private Point2D computeLayoutOrigin() {

        Dimension size = getSize();
        Point2D.Float origin = new Point2D.Float();

        origin.x = (float) (size.width - textLayout.getAdvance()) / 2;
        origin.y = (float) (size.height - textLayout.getDescent() + textLayout.getAscent()) / 2;
        return origin;
    }

    /**
     * Draw textLayout.
     */
    public void paint(Graphics g) {

        Graphics2D graphics2D = (Graphics2D) g;
        Point2D origin = computeLayoutOrigin();

        // Draw textLayout at origin.
        textLayout.draw(graphics2D, (float) origin.getX(), (float) origin.getY());
    }

    public static void main(String[] args) {

        AttributedCharacterIterator text = SampleUtils.getText(args);
        Component sample = new DrawSample(text);
        SampleUtils.showComponentInFrame(sample, "Draw Sample");
    }
}
