I know that you can import a Font in Java with something like this:
File file = new File(fontPath);
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
// alternative:
// Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(file));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
Then you would use for example font.deriveFont(Font.PLAIN, 20);
to get the desired style and size.
Example
But now let's look as an example at the font Consolas
, there you have four TTF files:
consola.ttf
(Plain)consolab.ttf
(Bold)consolai.ttf
(Italic)consolaz.ttf
(Bold & Italic)
Of course you could just import consola.ttf
with the method stated above, but then using font.deriveFont(Font.BOLD, 20);
isn't the same as using consolab.ttf
because the plain font was simply transformed to look like a bold font.
Example Pictures
- Here I used the installed font with
new Font("Consolas", Font.PLAIN, 20);
andnew Font("Consolas", Font.BOLD, 20);
(as a side note, if the font is installed on the system you also get the right bold font if you usederiveFont(Font.BOLD);
):
- And this is
consola.ttf
, imported withcreateFont
and derived bold font (both with size 20 like the example above):
Well when installed it isn't a problem, but I don't expect others to have a custom Font, so I want to put the TTFs into the jar file, so that I can import them during the initialization via getResourceAsStream(path)
.
Is there a way to import all relevant TTFs and then just call new Font("Custom Font Name", fontStyle, fontSize);
so that it's used like an installed font (Picture 1), and that it doesn't looks like a derived 'fake' bold font (Picture 2)?