Calculates the average character width for the given Component . - Java Swing

Java examples for Swing:JComponent

Description

Calculates the average character width for the given Component .

Demo Code

/*/*from  www. j  ava 2s  .  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.
 */
//package com.java2s;
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 Tutorials