Java tutorial
//package com.java2s; /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ import java.awt.*; public class Main { /** * Returns the size of the given text computed towards to the given * component. * * @param c the component where the text is contained * @param text the text to measure * @return the dimensions of the text */ public static Dimension getStringSize(Component c, String text) { // get metrics from the graphics FontMetrics metrics = c.getFontMetrics(c.getFont()); // get the height of a line of text in this font and render context int hgt = metrics.getHeight(); // get the advance of my text in this font and render context int adv = metrics.stringWidth(text); // calculate the size of a box to hold the text with some padding. return new Dimension(adv + 2, hgt + 2); } }