centering Text - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

centering Text

Demo Code


//package com.java2s;
import java.awt.*;

import java.awt.geom.*;

public class Main {
    public static int[] centeringText(String s, Font f, int width,
            int height, Graphics2D g) {
        //Interesting centering in a box, using FontMetrics to see how big our font is.
        FontMetrics fm = g.getFontMetrics(f);
        Rectangle2D rect = fm.getStringBounds(s, g);
        int[] ret = new int[2];
        ret[0] = (width - (int) (rect.getWidth())) / 2;
        ret[1] = (height - (int) (rect.getHeight())) / 2 + fm.getAscent();
        //ret has [x,y];
        return ret;
    }/*from w ww  .  j a  va  2s.co m*/
}

Related Tutorials