Adding fonts to Swing application and include in package
Asked Answered
M

3

18

I need to use custom fonts (ttf) in my Java Swing application. How do I add them to my package and use them?

Mean while, I just install them in windows and then I use them, but I don't wish that the usage of the application will be so complicated, it`s not very convenient to tell the user to install fonts before using my application.

Muriel answered 21/10, 2012 at 14:13 Comment(3)
It maybe a duplicate question, see here.Cathode
@Muriel If you opened a bounty on purpose because you are not satisfied with the current answers, you should clarify why it does not answer your question and/or what additional information you need.Propagandize
possible duplicate of embedding a font in JavaCapps
H
28

You could load them via an InputStream:

InputStream is = MyClass.class.getResourceAsStream("TestFont.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);

This loaded font has no predefined font settings so to use, you would have to do:

Font sizedFont = font.deriveFont(12f);
myLabel.setFont(sizedFont);

See:

Physical and Logical Fonts

Horsepowerhour answered 21/10, 2012 at 14:18 Comment(3)
Where do i need to put the TestFont.ttf file?Muriel
For the example above it needs to be in same location as the class file.Horsepowerhour
Or if it is in a package, you can access it by the full package name. eg: i have ttf file foo.ttf in package foo.bar.master.cork, I would access it through getResourceAsStream("/foo/bar/master/cork/foo.ttf"). What this means is: put a forward slash at the start, replace every dot with a forward slash (except in the filename.), and a forward slash at the end of the path but before the file.Stalk
C
9

As Reimeus said, you can use an InputStream. You can also use a File:

File font_file = new File("TestFont.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, font_file);

In both cases you would put your font files in either the root directory of your project or some sub-directory. The root directory should probably be the directory your program is run from. For example, if you have a directory structure like:

My_Program
|
|-Fonts
| |-TestFont.ttf
|-bin
  |-prog.class

you would run your program with from the My_Program directory with java bin/prog. Then in your code the file path and name to pass to either the InputStream or File would be "Fonts/TestFont.ttf".

Custodial answered 21/10, 2012 at 14:39 Comment(0)
A
1

Try this:

@Override
public Font getFont() {
    try {
        InputStream is = GUI.class.getResourceAsStream("TestFont.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, is);
        return font;
    } catch (FontFormatException | IOException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        return super.getFont();
    }
}
Aggregate answered 22/8, 2014 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.