draw Centered String - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

draw Centered String

Demo Code


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

public class Main {
    public static void drawCenteredString(Graphics g, String text, int y,
            int width) {
        int[] widths = g.getFontMetrics().getWidths();
        for (String line : text.split("\n")) {
            int lineWidth = 0;
            for (final char c : line.toCharArray()) {
                lineWidth += widths[c];//from   ww  w  .j  a  v a  2  s  .c  o m
            }
            int x = (width - lineWidth) / 2;
            g.drawString(line, x, y);
            y += g.getFontMetrics().getHeight();
        }
    }

    public static void drawString(Graphics g, String text, int x, int y) {
        for (String line : text.split("\n")) {
            g.drawString(line, x, y += g.getFontMetrics().getHeight());
        }
    }
}

Related Tutorials