Java Font Text Size getStringSize(final Graphics g, final Font font, final String text)

Here you can find the source of getStringSize(final Graphics g, final Font font, final String text)

Description

get String Size

License

Open Source License

Declaration

public static Dimension getStringSize(final Graphics g,
            final Font font, final String text) 

Method Source Code

//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);
    }
}

Related

  1. getSize(Font font)
  2. getStringDimension(Component comp, String str)
  3. getStringDimensions(Graphics2D graphics, Font font, String[] stringsByLine)
  4. getStringDisplaySize(String input)
  5. getStringSize(Graphics g, String text, Font font)
  6. getStringSize(String textToMeasure, Font displayFont)
  7. getStringSizeForFont(final String string, final Font font)