roytang.net Posts Photos Archives About
gregm said...

I found the code here inadequate for my needs.

I needed to test an unknown input string, to determine what font to use, hence, I needed to check every single character. (see below)

By the way, the font.canDisplayUpTo method will not work. It may approve a font, that can only display some of the characters.

So, just use this code below.

Font[] allFonts;
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

allFonts = env.getAllFonts();

Font targetFont = null;
for ( int i = 0; i < allFonts.length; i++ ) 
{
    Font font = allFonts[ i ];
    boolean canDisplayAll = true;
    for (char c : text.toCharArray())
    {
        if (!font.canDisplay(c))
        {
            canDisplayAll = false;
            break;
        }
    }
    if (canDisplayAll)
    {
        logger.debug("font can display the text " + font.getName());
        targetFont = font;
        break;
    }
    else
    {
        logger.debug("cant display " + font.getName());
    }
}
via stackoverflow.com