Is there a way in Java to get the native font name from a Font
object?
I get my Font using this code Font.decode("Serif")
and for debugging purpose I would like to know the native font used.
It might not be that simple. Some fonts are composed of many physical fonts, using different physical fonts for different glyphs.
For example, on my Windows system the Serif font uses 12 physical fonts:
The following code can break down a font into its physical components. It uses a reflection hack to access a sun.awt.Font2D
object, so use at your own risk (works with Oracle Java 6u37):
import java.awt.Font;
import java.lang.reflect.Method;
import java.util.Locale;
import sun.font.CompositeFont;
import sun.font.Font2D;
import sun.font.PhysicalFont;
public class FontTester
{
public static void main(String... args)
throws Exception
{
Font font = new Font("Serif", Font.PLAIN, 12);
describeFont(font);
}
private static void describeFont(Font font)
throws Exception
{
Method method = font.getClass().getDeclaredMethod("getFont2D");
method.setAccessible(true);
Font2D f = (Font2D)method.invoke(font);
describeFont2D(f);
}
private static void describeFont2D(Font2D font)
{
if (font instanceof CompositeFont)
{
System.out.println("Font '" + font.getFontName(Locale.getDefault()) + "' is composed of:");
CompositeFont cf = (CompositeFont)font;
for (int i = 0; i < cf.getNumSlots(); i++)
{
PhysicalFont pf = cf.getSlotFont(i);
describeFont2D(pf);
}
}
else
System.out.println("-> " + font);
}
}
prunge's answer was nearly perfect, except that it didn't actually expose the native (physical) font's name. The following tiny change to the describeFont2D method does the trick by again leveraging Java reflection:
Don't forget to import java.lang.reflect.Field;
private static void describeFont2D( Font2D font ) throws Exception{
if( font instanceof CompositeFont ){
System.out.println( "Font '"+font.getFontName( Locale.getDefault() )+"' is composed of:" );
CompositeFont cf = ( CompositeFont )font;
for( int i = 0; i<cf.getNumSlots(); i++ ){
PhysicalFont pf = cf.getSlotFont( i );
describeFont2D( pf );
}
}else if( font instanceof CFont ){
Field field = CFont.class.getDeclaredField( "nativeFontName" );
field.setAccessible( true );
String nativeFontName = ( String )field.get( font );
System.out.println( "-> "+nativeFontName );
}else
System.out.println( "-> "+font );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With