By ComputerLocus


2011-12-03 01:34:53 8 Comments

I'm wondering how you would go about importing a font.

I'm trying to use a custom downloaded font but since most computers that would go to run this would not have this font as it's not a default font. How would I go about making the font work even if they don't have the font?

I'm using it for a gameover screen and need to display a score with it and want the score text to be the same font. This is the image,

enter image description here

In case it matters the font name on my computer is Terminal

Edit: I'm assuming it would have to have the font in the directory of the java file and there would be some way of using that but I'm not sure how. Or is there a better way?

Edit2: I have found a nice tutorial on how to do it but need some help on how I go about using this... click me for link

Edit3:

URL fontUrl = new URL("http://www.webpagepublicity.com/" + "free-fonts/a/Airacobra%20Condensed.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
g.setFont(font);

Error Message

File: F:\Computer Science\draw.java  [line: 252]
Error: F:\Computer Science\draw.java:252: font is not public in java.awt.Component; cannot be accessed from outside package

Here is what I'm trying:

URL fontUrl = new URL("http://img.dafont.com/dl/?f=badaboom_bb");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
g.setFont(font);

Edit4:

File fontfile = new File("TexasLED.ttf");
File.toURI(fontfile).toURL(fontfile);
URL fontUrl = new URL("fontfile");

Error

Error: F:\Computer Science\draw.java:250: toURI() in java.io.File cannot be applied to (java.io.File)

4 comments

@isu3ru 2016-10-04 04:52:41

You can use fonts embedded in your application jar file too. I have used this function for many years to load fonts in my projects.

public Font getFont(String fileName) throws Exception {
    String path = "/xyz/isururanawaka/wb/fonts/" + fileName;
    URL url = getClass().getResource(path);
    return Font.createFont(Font.TRUETYPE_FONT, new File(url.toURI()));
}

@Andrew Thompson 2011-12-03 02:34:48

'Airacobra Condensed' font available from Download Free Fonts.

Registered Font

import java.awt.*;
import javax.swing.*;
import java.net.URL;

class LoadFont {
    public static void main(String[] args) throws Exception {
        // This font is < 35Kb.
        URL fontUrl = new URL("http://www.webpagepublicity.com/" +
            "free-fonts/a/Airacobra%20Condensed.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
        GraphicsEnvironment ge = 
            GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(font);
        JList fonts = new JList( ge.getAvailableFontFamilyNames() );
        JOptionPane.showMessageDialog(null, new JScrollPane(fonts));
    }
}

OK, that was fun, but what does this font actually look like?

Display Font

import java.awt.*;
import javax.swing.*;
import java.net.URL;

class DisplayFont {
    public static void main(String[] args) throws Exception {
        URL fontUrl = new URL("http://www.webpagepublicity.com/" +
            "free-fonts/a/Airacobra%20Condensed.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
        font = font.deriveFont(Font.PLAIN,20);
        GraphicsEnvironment ge =
            GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(font);

        JLabel l = new JLabel(
            "The quick brown fox jumps over the lazy dog. 0123456789");
        l.setFont(font);
        JOptionPane.showMessageDialog(null, l);
    }
}

@ComputerLocus 2011-12-03 02:54:19

I tried using this: URL fontUrl = new URL("http://www.webpagepublicity.com/" + "free-fonts/a/Airacobra%20Condensed.ttf"); Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream()); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); }catch(Exception e) { } g.setFont(font); I got this error: font cannot be accessed from outside package

@ecle 2011-12-03 09:30:44

@AndrewThompson It would be nice to come up with a fallback mechanism just in case the user is unable to load the font from Internet especially when the font doesn't have any good system font to substitute it.

@Andrew Thompson 2011-12-03 10:26:53

@eee (sigh) The point about loading a Font off the net is ..not the point, since it is not what I am suggesting. The act of hot-linking to a Font was merely to create an SSCCE. Do you have a better way to demonstrate loading a custom Font in a code that is 'SC' (self-contained)? Personally I'd include the Font in a Jar that is added to the run-time class-path of the app.

@Andrew Thompson 2011-12-03 10:33:48

@eee ..continued after 5 min. limit. .. No fuss, no muss. OTOH the OP is insisting on a File based location, so some of my other comments (not necessarily on this answer) also refer to loading a Font from a File.

@ecle 2011-12-03 10:48:47

@AndrewThompson You point is taken... I just want to address the limitation of hot-linking a font in a non-networked environment. The best still is either to include the fonts inside a jar as resources or to get them from outside a jar (from a file directory or font file cache). It depends on font licensing as well. In my case with the current project, I am not allowed to embed licensed fonts inside a jar. So, I have to access the font files either from a special folder under the installation folder or to install them as system fonts so they can be used in the application.

@Andrew Thompson 2011-12-03 11:01:33

@eee "I just want to address the limitation of hot-linking a font in a non-networked environment." And that is a good point, thanks for high-lighting the perils. (re. Font licensing) "So, I have to access the font files either from a special folder" (shudder) That is unfortunate. Still, we gotta' do what we gotta' do. I won't begin to describe some of the licensing hoops I had to leap through in order to create a project based around 4 holy testaments. ;)

@ylun.ca 2014-04-09 21:51:35

This answer seems to work for only half the fonts on that site, any ideas why? Also, are there any other sites that this method can be used with? The fonts on the site provided are, imo, ugly.

@Andrew Thompson 2014-04-09 23:19:14

@ylun.za "any ideas why?" Provide an MCVE (Minimal Complete and Verifiable Example) that fails. "..are there any other sites that this method can be used with?" It was never intended that 'real world' apps get their fonts by hot-linking to an internet site! Download the font and include it in one of the application Jars.

@ylun.ca 2014-04-09 23:57:49

I see. And simply try another url; one that i found did not work was the "Amiga Forever" font.

@Andrew Thompson 2014-04-10 00:33:00

@ylun.za I'm not going searching that site for the font you mention. If you want me to try it, post an MCVE, like I did.

@ComputerLocus 2011-12-04 20:30:27

I have solved my own problem. I have done

URL fontUrl = new URL("file:///F:/Computer_Science/TexasLED.ttf");

That points to the font and works for me!

@Wouter Dorgelo 2011-12-03 01:39:32

You can use GraphicsEnvironment.registerFont

http://docs.oracle.com/javase/6/docs/api/java/awt/GraphicsEnvironment.html#registerFont(java.awt.Font)

With this you can load a font from a .ttf file:

private static final Font SERIF_FONT = new Font("serif", Font.PLAIN, 24);

private static Font getFont(String name) {
    Font font = null;
    if (name == null) {
        return SERIF_FONT;
    }

    try {
        // load from a cache map, if exists
        if (fonts != null && (font = fonts.get(name)) != null) {
            return font;
        }
        String fName = Params.get().getFontPath() + name;
        File fontFile = new File(fName);
        font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();

        ge.registerFont(font);

        fonts.put(name, font);
    } catch (Exception ex) {
        log.info(name + " not loaded.  Using serif font.");
        font = SERIF_FONT;
    }
    return font;
}

@Andrew Thompson 2011-12-03 10:31:04

@Mr.Pallazzo BTW - sorry for hi-jacking your answer. I feel that it should be your answer that gets the 'tick'. I just turned your suggestion into an SSCCE (or 2, with pretty screen-shots).

Related Questions

Sponsored Content

55 Answered Questions

[SOLVED] How do I fix 'android.os.NetworkOnMainThreadException'?

41 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

43 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

28 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1884738 View
  • 2184 Score
  • 28 Answer
  • Tags:   java arrays

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3903357 View
  • 3361 Score
  • 65 Answer
  • Tags:   java random integer

33 Answered Questions

[SOLVED] How do you assert that a certain exception is thrown in JUnit 4 tests?

57 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

21 Answered Questions

[SOLVED] How do I call one constructor from another in Java?

  • 2008-11-12 20:10:19
  • ashokgelal
  • 806507 View
  • 2134 Score
  • 21 Answer
  • Tags:   java constructor

32 Answered Questions

[SOLVED] Can I embed a custom font in an iPhone application?

  • 2008-12-11 20:21:11
  • Airsource Ltd
  • 235824 View
  • 771 Score
  • 32 Answer
  • Tags:   ios cocoa-touch fonts

3 Answered Questions

[SOLVED] File to URL for a Font

  • 2011-12-04 03:53:07
  • ComputerLocus
  • 684 View
  • 0 Score
  • 3 Answer
  • Tags:   java file fonts

Sponsored Content