measure String Width - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

measure String Width

Demo Code


//package com.java2s;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class Main {
    public static int measureStringWidth(Graphics g, String s) {
        return (int) g
                .getFont()/*from w  w  w.j  a v  a  2 s .c  om*/
                .getStringBounds(s, ((Graphics2D) g).getFontRenderContext())
                .getWidth();
    }

    public static int measureStringWidth(Graphics g, Font f, String s) {
        return (int) f.getStringBounds(s,
                ((Graphics2D) g).getFontRenderContext()).getWidth();
    }
}

Related Tutorials