Search code examples
javauser-interfacefontscompatibility

How can I use a downloaded font in a java Project on different PCs?


I downloaded the Font "Retro Gaming" (https://www.dafont.com/retro-gaming.font) to use it on my Java project. This project needs to run on every machine I run it. My question is: How or where can I put the font so that all computers (even without having it installed) can use it? I thought gradle could be a nice solution but I found nothing about it on the internet.

The example of code is:

public PlayerOneLabel() {
        this.setText("PLAYER 1");
        this.setForeground(Color.white);
        this.setFont(new Font("Retro Gaming", Font.BOLD, CenterOnDefaultScreen.center().height*2/100));
        }

This obviously run only on the PCs with the font already installed.


Solution

  • Save the font file wherever you like...place it with the rest of your game files or place it in a resource folder. It doesn't need to go somewhere special if it's just for your game. You can load the font when you need it by using the following method:

    /**
     * Loads a Font file and returns it as a Font Object. This method does try to 
     * utilize the proper Font Type Resource (TrueType or Type1) but will default 
     * to TrueType if the resource type can not be established.
     * 
     * @param fontFilePath (String) Full path and file name of the font to load.<br>
     * 
     * @param fontStyle (Integer) The Font Style to use for the loaded font, for 
     * example:<pre>
     * 
     *      Font.PLAIN
     *      Font.BOLD
     *      Font.ITALIC
     *      Font.BOLDITALIC</pre>
     * 
     * @param fontSize (Integer) The desired size of font.<br>
     * 
     * @return (Font) A Font Object
     */
    public Font loadFont(String fontFilePath, int fontStyle, int fontSize) {
        Font font = null;
        int fontTypeResource = Font.TRUETYPE_FONT;
        if ((fontFilePath == null || fontFilePath.isEmpty()) || fontSize < 1) {
            throw new IllegalArgumentException("loadFont() Method Error! Arguments "
                    + "passed to this method must contain a file path OR a numerical "
                    + "value other than 0!" + System.lineSeparator());
        }
        String fileExt = (fontFilePath.contains(".") ? fontFilePath.substring(fontFilePath.lastIndexOf(".") + 1) : "");
        if (fontFilePath.isEmpty()) {
            throw new IllegalArgumentException("loadFont() Method Error! An illegal "
                    + "font file has been passed to this method (no file name "
                    + "extension)!" + System.lineSeparator());
        }
        
        switch (fileExt.toLowerCase()) {
            case "fot":
            case "t2":
            case "otf":
            case "ttf":
                fontTypeResource = Font.TRUETYPE_FONT;
                break;
            // PostScript/Adobe
            case "lwfn":
            case "pfa":
            case "pfb":
            case "pdm":
                fontTypeResource = Font.TYPE1_FONT;
                break;
            default:
                fontTypeResource = Font.TRUETYPE_FONT;
        }
        
        try {
            font = Font.createFont(fontTypeResource, new FileInputStream(
                   new File(fontFilePath))).deriveFont(fontStyle, fontSize);
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger("loadFont()").log(Level.SEVERE, null, ex);
        }
        catch (FontFormatException | IOException ex) {
            Logger.getLogger("loadFont()").log(Level.SEVERE, null, ex);
        }
        return font;
    }
    

    And how you might use it:

    JLabel jLabel_1 = new JLabel("This is my Label Caption");
    
    /* Assumes the .ttf file in within the application's project 
       directory. Use a getResource() mechanism when loading from
       a resource directory.                           */
    Font gameFont = loadFont("Retro Gaming.ttf", Font.BOLD, 18);
    
    jLabel_1.setFont(gameFont);