How does one load a logical fonts physical font? (Making a JComboBox font chooser)

家住魔仙堡 提交于 2019-12-24 00:40:02

问题


Followup question from this one: Swing font names do not match? (Making a font chooser, and am trying to display the default system font in a JComboBox)

It appears there are logical and physical fonts. The logical fonts are: Serif, SansSerif, Monospaced, Dialog, and DialogInput.

These fonts are dynamic, and their respective physical font (the font that they will represent during program execution) are decided when the program loads.

I need to access the physical font of these logical fonts.

My first idea was to try and load these files: http://download.oracle.com/javase/6/docs/technotes/guides/intl/fontconfig.html#loading

by using something like this: http://www.rgagnon.com/javadetails/java-0434.html

public static Properties load(String propsName) throws Exception {
    Properties props = new Properties();
    URL url = ClassLoader.getSystemResource(propsName);
    props.load(url.openStream());
    return props;
}

and then getting the physical fonts from these properties files.

However, I am just getting NullPointerExceptions when trying to load the properties using the names in the first file (they are not found, but I have checked and actually found them on my system). I don't know why I am getting this, but regardless of that, I can't help to think there must be an easier way to do this?


回答1:


public static Font getPhysicalFont(Font logicalFont) {
    for (int i=0; i<FontManager.getRegisteredFonts().length; i++) {
        Font2D font = FontManager.getRegisteredFonts()[i];
        if (font instanceof CompositeFont && font.getFontName(Locale.getDefault()).equals(logicalFont.getFontName())) {
            PhysicalFont physicalFont = ((CompositeFont) font).getSlotFont(0);
            return new Font(physicalFont.getFamilyName(Locale.getDefault()), physicalFont.getStyle(), logicalFont.getSize());
        }
    }
    return logicalFont;
}


来源:https://stackoverflow.com/questions/6002051/how-does-one-load-a-logical-fonts-physical-font-making-a-jcombobox-font-choose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!