by BehindJava

How to get the width and height of a string in Java

Home » java » How to get the width and height of a string in Java

In this tutorial, We are going to learn about getting the width and height of a string in Java using AWT.

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

public class BehindJava {
	public static void main(String[] args) {
		String text = "Behind Java";
		Font font = new Font("Arial", Font.PLAIN, 12);
		FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);

		int textwidth = (int) (font.getStringBounds(text, frc).getWidth());
		int textheight = (int) (font.getStringBounds(text, frc).getHeight());
		System.out.println("width:" + textwidth + "height:" + textheight);
	}
}

Output:

width:66height:13