get Font File - Java 2D Graphics

Java examples for 2D Graphics:Font

Description

get Font File

Demo Code

/*//  w  ww . ja v  a  2 s  . c o  m
 *  Copyright (C) 2010-2015 JPEXS, All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 */
//package com.java2s;
import java.awt.Font;

import java.io.File;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Main {
    public static File getFontFile(Font f) {
        try {
            Class pfClass = Class.forName("sun.font.PhysicalFont");
            Field platName = pfClass.getDeclaredField("platName");
            platName.setAccessible(true);
            String fontPath = (String) platName.get(getFont2d(f));
            platName.setAccessible(false);
            return new File(fontPath);
        } catch (Throwable e) {
            return null;
        }
    }

    private static Object getFont2d(Font f) throws ClassNotFoundException,
            NoSuchMethodException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Object fm = getFontManager();
        return Class
                .forName("sun.font.FontManager")
                .getDeclaredMethod("findFont2D", String.class, int.class,
                        int.class)
                .invoke(fm, f.getFontName(), f.getStyle(), 2/*LOGICAL_FALLBACK*/);
    }

    private static Object getFontManager() throws ClassNotFoundException,
            NoSuchMethodException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Class<?> clFmFactory = Class.forName("sun.font.FontManagerFactory");
        return clFmFactory.getDeclaredMethod("getInstance").invoke(null);
    }
}

Related Tutorials