Java FontMetrics getMonospacedFontsFamillyName()

Here you can find the source of getMonospacedFontsFamillyName()

Description

get Monospaced Fonts Familly Name

License

Open Source License

Return

String[0] is the monospaced fonts and String[1] the non-monospaced

Declaration

public static String[][] getMonospacedFontsFamillyName() 

Method Source Code

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

import java.awt.Font;

import java.awt.GraphicsEnvironment;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;

public class Main {
    private static Graphics2D g2d;
    private static int defaultFontSize = 14;

    /**//from www . ja v  a 2  s  .c om
     * @return String[0] is the monospaced fonts and String[1] the non-monospaced
     */
    public static String[][] getMonospacedFontsFamillyName() {
        String[] fontFamilly = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
        List<String> mono = new ArrayList();
        List<String> notMono = new ArrayList();
        for (int i = 0; i < fontFamilly.length; i++) {
            if (isMonospaced(fontFamilly[i])) {
                mono.add(fontFamilly[i]);
            } else {
                notMono.add(fontFamilly[i]);
            }
        }

        return new String[][] { mono.toArray(new String[0]), notMono.toArray(new String[0]) };
    }

    /**
     * @param fontName the font name to test
     * @return true if the font is monospaced
     */
    public static boolean isMonospaced(String fontName) {
        return isMonospaced(new Font(fontName, Font.PLAIN, defaultFontSize));
    }

    /**
     * @param font the font to test
     * @return true if the font is monospaced
     */
    public static boolean isMonospaced(Font font) {
        int[] arr = g2d.getFontMetrics(font).getWidths();
        int w = arr['a'];
        // The range 33--126 corresponds to the usual characters in ASCII
        for (int i = 33; i < 127; i++) {
            if (arr[i] != w) {
                return false;
            }
        }

        return true;
    }
}

Related

  1. getLineHeight(FontMetrics fm)
  2. getLongestStringWidth(FontMetrics fm, String[] theStrings)
  3. getMaxFittingFontSize(Graphics g, Font font, String string, Dimension size)
  4. getMaxFontHeight(final java.awt.Font font)
  5. getMonospacedFontNames()
  6. getPrefSize(FontMetrics fm, String keyTip)
  7. getStringForMaxWidth(FontMetrics fm, String s, int maxWidth)
  8. getStringImage(Font font, String... strs)
  9. getStringLengthInPixels(String s, Graphics g)