DanM
DanM

Reputation: 1540

Adding fonts to Swing application and include in package

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.

Upvotes: 18

Views: 25269

Answers (3)

Ahmad R. Nazemi
Ahmad R. Nazemi

Reputation: 805

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();
    }
}

Upvotes: 1

Reimeus
Reimeus

Reputation: 159754

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

Upvotes: 28

event44
event44

Reputation: 618

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".

Upvotes: 9

Related Questions