Strange font behavior after GraphicsEnvironment # getAvailableFontFamilyNames ()?

I just came across a very strange behavior of the Java font class.

If I create a simple font of the Verdana family, for example,

Font font = new Font("Verdana", Font.PLAIN, 12);

I expect this font to be a non-bold font that refers to the simple Verdan font installed on my system. I am using Windows 7, so the corresponding font should be "verdana.ttf" in the "Windows / Fonts" folder.

While this works, the font instance changes its behavior if I call

GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

before the font is used (i.e. before the font is attached to any system font). In this case, the font seems to refer to the Verdana Bold font ("verdanab.ttf") on my system.

Here are some test codes that reproduce this problem:

import java.awt.Font;
import java.awt.GraphicsEnvironment;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class JavaFontBug {

    public static void main(String[] args) {

        boolean enableStrangeBug = false;
        Font font = new Font("Verdana", Font.PLAIN, 12);

        String text;
        if (enableStrangeBug) {
            // this line enables the bug:
            GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
            text = "Some Bold Text?!";
        } else{
            text = "Some Text";
        }

        System.out.println("Font: " + font);
        System.out.println("Font name: " + font.getFontName());

        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel(text);
        label.setFont(font);
        frame.getContentPane().add(label);
        frame.pack();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
    }

}

enableStrangeBug false, , "Some Text" "Verdana". :

Font: java.awt.Font[family=Verdana,name=Verdana,style=plain,size=12]
Family: Verdana
Name: Verdana
Font name: Verdana
PS name: Verdana

enableStrangeBug, , true, "Verdana Bold", :

Font: java.awt.Font[family=Verdana,name=Verdana,style=plain,size=12]
Family: Verdana
Name: Verdana
Font name: Verdana Bold
PS name: Verdana-Bold

, , , . Windows 7, Java 7 Java 8. "Fonts" Verdana: verdana.ttf, verdanab.ttf, verdanai.ttf verdanaz.ttf.

JComboBox , , : JComboBox GraphicsEnvironment#getAvailableFontFamilyNames(), , , .

- , JComboBox ?

: - , ? , "", , , Tahoma . , Times New Roman Arial, , ...


UPDATE

- Java , :

static{
    for (Font f : GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()) {
        f.getPSName();
    }
}

, , , , / .

+4

Source: https://habr.com/ru/post/1539263/


All Articles