Here you can find the source of getStringSize(final Graphics g, final Font font, final String text)
public static Dimension getStringSize(final Graphics g, final Font font, final String text)
//package com.java2s; /******************************************************************************* * Copyright (C) 2014 University of Massachusetts Medical School * Alessandro Rigano (Program in Molecular Medicine) * Caterina Strambio De Castillia (Program in Molecular Medicine) * * Created by the Open Microscopy Environment inteGrated Analysis (OMEGA) team: * Alex Rigano, Caterina Strambio De Castillia, Jasmine Clark, Vanni Galli, * Raffaello Giulietti, Loris Grossi, Eric Hunter, Tiziano Leidi, Jeremy Luban, * Ivo Sbalzarini and Mario Valle.// w ww .ja v a 2 s .co m * * Key contacts: * Caterina Strambio De Castillia: caterina.strambio@umassmed.edu * Alex Rigano: alex.rigano@umassmed.edu * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; public class Main { public static Dimension getStringSize(final Graphics g, final Font font, final String text) { // get metrics from the graphics final FontMetrics metrics = g.getFontMetrics(font); // get the height of a line of text in this // font and render context final int hgt = metrics.getHeight(); // get the advance of my text in this font // and render context final 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); } }