Java FontMetrics getComponentAverageCharacterWidth(Component component)

Here you can find the source of getComponentAverageCharacterWidth(Component component)

Description

Calculates the average character width for the given Component .

License

Open Source License

Parameter

Parameter Description
component the Component for which to calculate the average character width.

Return

The average width in pixels

Declaration

public static float getComponentAverageCharacterWidth(Component component) 

Method Source Code


//package com.java2s;
/*//from   w w w  .j  a  v  a2s. c  o m
 * Universal Media Server, for streaming any medias to DLNA
 * compatible renderers based on the http://www.ps3mediaserver.org.
 * Copyright (C) 2012 UMS developers.
 *
 * This program is a 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; version 2
 * of the License only.
 *
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

import java.awt.Component;

import java.awt.FontMetrics;

public class Main {
    /**
     * Calculates the average character width for the given {@link Component}.
     * This can be useful as a scaling factor when designing for font scaling.
     *
     * @param component the {@link Component} for which to calculate the
     *        average character width.
     * @return The average width in pixels
     */
    public static float getComponentAverageCharacterWidth(Component component) {
        FontMetrics metrics = component.getFontMetrics(component.getFont());
        int i = 0;
        float avgWidth = 0;
        for (int width : metrics.getWidths()) {
            avgWidth += width;
            i++;
        }
        return avgWidth / i;
    }
}

Related

  1. clipString(Graphics g, String t, int width)
  2. cutString(String text, FontMetrics fontMetrics, int maxWidth)
  3. fitString(String s, Graphics2D g2, Rectangle2D rect)
  4. getAllStylesSameWidthsFontsFamillyName()
  5. getCenterOffset(Graphics g, Font f, char ch)
  6. getConsoleFontMetrics(Font font)
  7. getLineBreakIndex(Graphics g, String text, int index, double maxWidth)
  8. getLineHeight(Component c, int defaultHeight)
  9. getLineHeight(Component c, int defaultHeight)