Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Fonts in Java

How to fix problem with custom fonts in Java?

For example, my app uses font, that isn't on all computers. Can I somehow include it in compiled executable and then call it from there, if it doesn't exists on clients computer?

What are other alternatives? I could make all fonts chars as images (before, in some graphics app) and then display image for each char... is it ok?

like image 301
daGrevis Avatar asked May 05 '11 18:05

daGrevis


People also ask

How do I get different fonts in Java?

properties files in the lib subdirectory under java. home. These localized font files allow you to remap the “Serif”, “SansSerif”, and “Monospaced” names to different fonts. The font's style is passed with the help of the class variables Font.

Can you add fonts to Java?

To add your own font to your JDK 1.1 Runtime, you need to create a charset converter and specify it in the font. properties file . The following example illustrates how to add your own platform font to the Java serif font. In this example, your font contains 256 glyphs, which are indexed 0 - 0xff.

How font is created in Java?

It creates a new Font object by replicating the current Font object and applying a new size to it. It creates a new Font object by replicating the current Font object and applying a new style to it. It creates a new Font object by replicating this Font object and applying a new style and transform.


2 Answers

Here's an utility method I'm using to load a font file from a .ttf file (can be bundled):

private static final Font SERIF_FONT = new Font("serif", Font.PLAIN, 24);

private static Font getFont(String name) {
    Font font = null;
    if (name == null) {
        return SERIF_FONT;
    }

    try {
        // load from a cache map, if exists
        if (fonts != null && (font = fonts.get(name)) != null) {
            return font;
        }
        String fName = Params.get().getFontPath() + name;
        File fontFile = new File(fName);
        font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();

        ge.registerFont(font);

        fonts.put(name, font);
    } catch (Exception ex) {
        log.info(name + " not loaded.  Using serif font.");
        font = SERIF_FONT;
    }
    return font;
}
like image 82
Bozho Avatar answered Sep 30 '22 13:09

Bozho


You can include the font with you application and create it "on-the-fly"

InputStream is = this.getResourceAsStream(font_file_name);
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
like image 24
Serhiy Avatar answered Sep 30 '22 14:09

Serhiy