Java tutorial
//package com.java2s; /* * 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; } }