Java Font from System getAllAvaiableSystemMonoSpacedFonts()

Here you can find the source of getAllAvaiableSystemMonoSpacedFonts()

Description

get All Avaiable System Mono Spaced Fonts

License

Apache License

Declaration

private static Set<Font> getAllAvaiableSystemMonoSpacedFonts() 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.Font;

import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;

import java.util.HashSet;

import java.util.Set;

public class Main {
    private static final float DEFAULT_FONT_SIZE = 12f;

    private static Set<Font> getAllAvaiableSystemMonoSpacedFonts() {
        Set<Font> monospacedFonts = new HashSet<Font>();

        GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontFamilyNames = graphicsEnvironment.getAvailableFontFamilyNames();

        BufferedImage bufferedImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics graphics = bufferedImage.createGraphics();

        for (String fontFamilyName : fontFamilyNames) {
            boolean isMonospaced = true;

            int fontStyle = Font.PLAIN;
            Font font = new Font(fontFamilyName, fontStyle, (int) DEFAULT_FONT_SIZE);
            FontMetrics fontMetrics = graphics.getFontMetrics(font);

            if (font.canDisplay('a')) {
                int firstCharacterWidth = 0;
                boolean hasFirstCharacterWidth = false;
                for (int codePoint = 0; codePoint < 128; codePoint++) {
                    if (Character.isValidCodePoint(codePoint)
                            && (Character.isLetter(codePoint) || Character.isDigit(codePoint))) {
                        char character = (char) codePoint;
                        int characterWidth = fontMetrics.charWidth(character);
                        if (hasFirstCharacterWidth) {
                            if (characterWidth != firstCharacterWidth) {
                                isMonospaced = false;
                                break;
                            }/*w  w  w .  j a v  a  2  s .co  m*/
                        } else {
                            firstCharacterWidth = characterWidth;
                            hasFirstCharacterWidth = true;
                        }
                    }
                }

                if (isMonospaced) {
                    monospacedFonts.add(font.deriveFont(Font.PLAIN));
                    monospacedFonts.add(font.deriveFont(Font.BOLD));
                    monospacedFonts.add(font.deriveFont(Font.ITALIC));
                }
            }
        }

        graphics.dispose();
        return monospacedFonts;
    }
}

Related

  1. availableFonts()
  2. getAllAvailableFonts()
  3. getAllFontNames()
  4. getDefaultBorderInsets(int fontSize)
  5. getDefaultFont()