Search code examples
javaswingfontsdefaultjcombobox

How to set the system default font as the selected item of JComboBox<String>?


This answer tells that using the constants Font.SERIF and Font.SANS_SERIF gives the default font of the system. That is OK; but if I have a JComboBox<String> that is filled by all of the font names of the system - then how to set correctly the JComboBox#setSelectedItem to the system default font?!

I tried: setSelectedItem(Font.SANS_SERIF); and setSelectedItem(Font.SERIF); but the JComboBox always selects the very first font name of the fonts list returned via GraphicsEnvironment, and not the system default font.

SSCCE:

import java.awt.*;
import javax.swing.*;

public class FontsExample extends JFrame {

    JComboBox<String> combo_fonts;
    GraphicsEnvironment ge;

    public FontsExample() {

        combo_fonts = new JComboBox<String>();

        ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

        for (Font font : ge.getAllFonts()) {
            combo_fonts.addItem(font.getFontName());
        }

        combo_fonts.setSelectedItem(Font.SANS_SERIF);

        JPanel panel = new JPanel();
        panel.add(combo_fonts);

        add(panel);

        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                FontsExample fontsExample = new FontsExample();
            }
        });
    }
}

Solution

  • The logical fonts don't seem to be listed among those returned by getAllFonts(). On the other hand, this works.

        ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        combo_fonts = new JComboBox<String>(ge.getAvailableFontFamilyNames());
        combo_fonts.setSelectedItem(Font.SANS_SERIF);