Java Swing Font Size ScaleLabelFontsizeAndDimension(JLabel label, int fontSize)

Here you can find the source of ScaleLabelFontsizeAndDimension(JLabel label, int fontSize)

Description

Scale Label Fontsize And Dimension

License

Apache License

Declaration

public static double ScaleLabelFontsizeAndDimension(JLabel label, int fontSize) 

Method Source Code

//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;
    }
}

Related

  1. increaseFontSize(JComponent component, int offset)
  2. printDocumentMonospaced(Graphics g, Document doc, int fontSize, int pageIndex, PageFormat pageFormat, int tabSize)
  3. printDocumentMonospacedWordWrap(Graphics g, Document doc, int fontSize, int pageIndex, PageFormat pageFormat, int tabSize)
  4. resetUIFont(String name, int style, int size)
  5. resetUIFontSize(int size)
  6. setFontSize(JLabel label, int i)
  7. setFontSizeForComponent(JComponent component, int newFontSize)
  8. setLookAndFeel(int fontSize)
  9. setUIFontSize(float size)