'Replace existing font definition in Swing

Our application use the custom font "Roboto". This font is stored in our jar and goes installed via following code:

final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, resourceClass.getResourceAsStream(font)));

Last time some our customers report a painting issue (some texts in tables are cut). After research we'v found that these customers got a software update that includes the Roboto font. When we delete this installed font all works fine. It looks like the existing (and probably unsuitable for us) font will not be replaced with our font (I've decompiled the class SunFontManager and it looks that's true). Have somebody an idea how to replace an existing font?



Solution 1:[1]

Make the Font object itself available through a public method. Change your code to use that object, rather than creating new Font objects using the family name.

For instance:

public class Fonts {
    private static Font robotoFont;

    public static Font getRobotoFont(int style,
                                     float size) {
        if (robotFont == null)  {
            final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            robotoFont = Font.createFont(Font.TRUETYPE_FONT, resourceClass.getResourceAsStream(font));
        }

        return robotoFont.deriveFont(style, size);
    }
}

Once you have that, you will want to replace every new Font("Roboto"… occurrence in the application. For instance, change this:

label.setFont(new Font("Roboto", Font.PLAIN, 12));

to this:

label.setFont(Fonts.getRobotoFont(Font.PLAIN, 12));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VGR