简体   繁体   中英

Importing Fonts from JAR file

I've attempted to create a custom font using the following method, however it throws an exception :

Stream closed

and nothing happens! How can I import a ttf file from my JAR and use it in Java 2D! I'v managed to get it to work with external files, but it just doesn't work with an InputStream!

 public Font gameFont(String filename, float fontSize) {
    Font myfont = null;
     Font myfontReal = null;
    try {
        InputStream is = new BufferedInputStream(this.getClass().getResourceAsStream("com/or/dungeon/" + filename));

        myfont = Font.createFont(Font.TRUETYPE_FONT, is);
        myfontReal = myfont.deriveFont(fontSize);
        is.close();
    } catch (FontFormatException | IOException e) {
        System.out.println(e.getMessage());
    }
    return myfontReal;
}

You are missing a leading slash. Without it, it is searching relative to the class making the call. Try:

this.getClass().getResourceAsStream("/com/or/dungeon/" + filename));

Alternatively, try:

this.getClass().getClassLoader().getResourceAsStream("com/or/dungeon/" + filename));

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