Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a custom font in Java?

Tags:

java

fonts

I wrote a program in Java that uses a special font that by default doesn't exist on any operating system.

Is it possible in Java to add this special font to the operation system? For example, in Windows, to copy this font to the special Fonts folder.

If it is possible, how?

like image 376
Mahdi_Nine Avatar asked Apr 13 '11 16:04

Mahdi_Nine


People also ask

How do I use new fonts in Java?

createFont(Font. TRUETYPE_FONT, new File("A. ttf"))); After this step is done, the font is available in calls to getAvailableFontFamilyNames() and can be used in font constructors.

What fonts can you use in Java?

Logical fonts are the five font families defined by the Java platform which must be supported by any Java runtime environment: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries.


2 Answers

If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:

Oracle Java SE 6: java.awt.Font

There is a tutorial available from Oracle that shows this example:

try {      GraphicsEnvironment ge =           GraphicsEnvironment.getLocalGraphicsEnvironment();      ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"))); } catch (IOException|FontFormatException e) {      //Handle exception } 

I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.

An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.

like image 133
Cᴏʀʏ Avatar answered Oct 11 '22 19:10

Cᴏʀʏ


Here is how I did it!

//create the font  try {     //create the font to use. Specify the size!     Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);     GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();     //register the font     ge.registerFont(customFont); } catch (IOException e) {     e.printStackTrace(); } catch(FontFormatException e) {     e.printStackTrace(); }  //use the font yourSwingComponent.setFont(customFont); 
like image 36
Florin Virtej Avatar answered Oct 11 '22 20:10

Florin Virtej