Java JTextComponent biggestFont(final javax.swing.text.JTextComponent c)

Here you can find the source of biggestFont(final javax.swing.text.JTextComponent c)

Description

Gets the biggest font that will fit in the text component.

License

Open Source License

Parameter

Parameter Description
c the JTextComponent for which to get the biggest font.

Return

The biggest for JTextComponent c

Declaration

public static Font biggestFont(final javax.swing.text.JTextComponent c) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.Font;

public class Main {
    /**/*from   ww  w. ja v a 2  s  .com*/
     * Gets the biggest font that will fit in the text component.
     * @param c the {@link JTextComponent} for which to get the biggest font.
     * @return The biggest {@link Font} for JTextComponent c
     */
    public static Font biggestFont(final javax.swing.text.JTextComponent c) {
        Font labelFont = c.getFont();
        String labelText = c.getText();

        int stringWidth = c.getFontMetrics(labelFont).stringWidth(labelText);
        int componentWidth = c.getWidth();

        // Find out how much the font can grow in width.
        double widthRatio = (double) componentWidth / (double) stringWidth;

        int newFontSize = (int) Math.floor(labelFont.getSize() * widthRatio);
        int componentHeight = c.getHeight();

        // Pick a new font size so it will not be larger than the height of label.
        int fontSizeToUse = Math.min(newFontSize, componentHeight);

        // Set the label's font size to the newly determined size.
        return new Font(labelFont.getName(), labelFont.getStyle(), fontSizeToUse);
    }
}

Related

  1. addTextUpdateListener(JTextComponent textComponent, Consumer listener)
  2. addUndoRedo(JTextComponent comp)
  3. adjustForLineComment(JTextComponent editor, int iStart)
  4. appendToText(JTextComponent textComp, String s)
  5. applyDefaultProperties(final JTextComponent comp)
  6. clear(JTextComponent... fields)
  7. currentLineChanged(final JTextComponent c)
  8. enableJTextField(JTextComponent component, boolean enable, Color color)
  9. ensureCustomBackgroundStored(JTextComponent comp)