draw Right Aligned String - Java java.awt

Java examples for java.awt:Graphics2D

Description

draw Right Aligned String

Demo Code


import org.apache.log4j.Logger;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.util.*;
import java.util.regex.Pattern;

public class Main{
    public static final float drawRightAlignedString(Graphics2D g,
            String string, Font font, float x, float y) {
        float startX = x - getTextWidth(g, string, font);
        return drawString(g, string, font, startX, y);
    }//from  ww w .j  a  v a2 s .com
    public static final float getTextWidth(Graphics2D g, String string,
            Font font) {
        return g.getFontMetrics(font).stringWidth(string);
    }
    public static final float drawString(Graphics2D g, String string,
            Font font, float x, float y) {
        g.setFont(font);
        y += font.getLineMetrics(string, g.getFontRenderContext())
                .getAscent();
        g.drawString(string, x, y);
        return getTextHeight(g, string, font);
    }
    public static final float getTextHeight(Graphics2D g, String string,
            Font font) {
        LineMetrics lm = font.getLineMetrics(string,
                g.getFontRenderContext());
        return lm.getHeight();
    }
}

Related Tutorials