简体   繁体   中英

Add custom font file on java for executable JAR file

I am trying to add custom font to my jswing application, and i can't find how to properly upload the.ttf file so that i can use it once i create a executable jar file.

problem here, new File(getClass().getResourceAsStream("/"+"cs_regular.ttf"))

thank you!

try {
         GraphicsEnvironment ge = 
             GraphicsEnvironment.getLocalGraphicsEnvironment();
         ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(getClass().getResourceAsStream("/"+"cs_regular.ttf"))));
    } catch (FontFormatException|IOException e) {
         pr("Error_107");
    }

It is not quite easy to create java.io.File from stream, you can create Font from stream directly. look at this answer. https://stackoverflow.com/a/40862139/10999348

This is my working code now

InputStream stream =ClassLoader.getSystemClassLoader().getResourceAsStream("cs_regular.ttf");
    try {
        csfont = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f);
    } catch (FontFormatException|IOException e) {
        //handle exeption
    } 
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.registerFont(csfont);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM