Here you can find the source of ScaleLabelFontsizeAndDimension(JLabel label, int fontSize)
public static double ScaleLabelFontsizeAndDimension(JLabel label, int fontSize)
//package com.java2s; //License from project: Apache License import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.swing.JLabel; public class Main { private static Graphics2D m_TempGraphics; public static double ScaleLabelFontsizeAndDimension(JLabel label, int fontSize) { Font fontLabel = label.getFont(); Font newFont = new Font(fontLabel.getName(), fontLabel.getStyle(), fontSize); double scaleFactor = fontSize / fontLabel.getSize(); double scaleFactorWidth = getGraphicsFontWidthAvg(newFont) / getGraphicsFontWidthAvg(fontLabel); label.setFont(newFont);// w w w . j av a2 s. c o m if (label.getSize().getWidth() > 0) label.setSize((int) (label.getSize().getWidth() * scaleFactorWidth), fontSize); else label.setPreferredSize( new Dimension((int) (label.getPreferredSize().getWidth() * scaleFactorWidth), fontSize)); return scaleFactor; } public static double getGraphicsFontWidthAvg(Font f) { int[] widths = getTempGraphics().getFontMetrics(f).getWidths(); int sum = 0; for (int d : widths) sum += d; return 1.0d * sum / widths.length; } private static Graphics2D getTempGraphics() { if (m_TempGraphics == null) { BufferedImage imgtext = new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB); m_TempGraphics = imgtext.createGraphics(); } return m_TempGraphics; } }