Java Swing Font Width getTextWidth(final String text, final Font font)

Here you can find the source of getTextWidth(final String text, final Font font)

Description

Gets the text width.

License

Apache License

Parameter

Parameter Description
text the text
font the font

Return

the text width

Declaration

public static int getTextWidth(final String text, final Font font) 

Method Source Code

//package com.java2s;
/*//from  w w w. j  ava 2s .co m
 * Copyright 2002-2016 Jalal Kiswani.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.Font;

import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

import javax.swing.UIManager;

public class Main {
    /**
     * Gets the text width.
     *
     * @param text
     *            the text
     * @param bold
     *            the bold
     * @return the text width
     */
    public static int getTextWidth(final String text, final boolean bold) {
        Font font = UIManager.getFont("Label.font");
        if (bold) {
            font = font.deriveFont(Font.BOLD);
        }
        return getTextWidth(text, font);
    }

    /**
     * Gets the text width.
     *
     * @param text
     *            the text
     * @param font
     *            the font
     * @return the text width
     */
    public static int getTextWidth(final String text, final Font font) {
        // final JLabel lbl = new JLabel(text);
        // lbl.setBorder(g);
        // lbl.setFont(font);
        // return (int) lbl.getPreferredSize().getWidth();
        AffineTransform affinetransform = new AffineTransform();
        FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
        int textwidth = (int) (font.getStringBounds(text, frc).getWidth());
        int textheight = (int) (font.getStringBounds(text, frc).getHeight());
        return textwidth;
    }
}

Related

  1. estimateWidth(Font font, String msg)
  2. getEditor(String html, int width, Color transparentColor, Font font)
  3. getHTMLTextForWidth(JComponent comp, double bboxWth, String txt, Font font)
  4. getStringWidth(final Font aFont, final String aString)
  5. getStringWidth(Font font, String str)
  6. getTextWidth(Font font, String text)
  7. isFixedWidthFont(String fontName, Component component)