Here you can find the source of getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine)
public static Dimension getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine)
//package com.java2s; //License from project: Apache License import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import java.text.AttributedString; public class Main { private final static String NEWLINE_SEPARATOR = System.getProperty("line.separator"); public static Dimension getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine) { FontMetrics fontMetrics = graphics.getFontMetrics(font); int overallWidth = 0; int overallHeight = 0; for (String string : stringsByLine) { int width = fontMetrics.stringWidth(string); int height = fontMetrics.getHeight(); overallWidth = Math.max(overallWidth, width); overallHeight += height;/*ww w.j a va 2s . c om*/ } return new Dimension(overallWidth, overallHeight); } public static Dimension getStringDimensions(Graphics2D graphics, Font font, String string) { FontMetrics fontMetrics = graphics.getFontMetrics(font); String[] lines = string.split(NEWLINE_SEPARATOR); // count the number of newlines in text int numberOfLines = lines.length; int heightOfOneLine = fontMetrics.getHeight(); int totalHeight = numberOfLines * heightOfOneLine; int maxWidth = 0; for (String line : lines) { maxWidth = Math.max(fontMetrics.stringWidth(line), maxWidth); } return new Dimension(maxWidth, totalHeight); } public static Dimension getStringDimensions(Graphics2D graphics, AttributedString attributedString) { TextLayout textLayout = new TextLayout(attributedString.getIterator(), graphics.getFontRenderContext()); Rectangle2D bounds = textLayout.getBounds(); return new Dimension((int) bounds.getWidth(), (int) bounds.getHeight()); } }