1

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();
            }
        });
    }
}
Community
  • 1
  • 1
Saleh Feek
  • 2,048
  • 8
  • 34
  • 56
  • What did you expect the list to select? Does it actually contain a font name `SansSerif` or `Serif`? From my testing to seems to work just fine – MadProgrammer Feb 29 '16 at 10:34
  • @MadProgrammer - the selected item is always "Agency FB" - it is not my system default. "Agency FB" is the first item of the fonts list returned via `GraphicsEnvironment` - That is why it is put as the selected - and not because of using `JComboBox#setSelectedItem` - If I remove the `setSelectedItem` line - it gives the same font "Agency FB" – Saleh Feek Feb 29 '16 at 10:40

1 Answers1

2

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);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Thanks; your solution works as required. I also tried another solution while still using `getAllFonts()`: in the loop that adds the fonts - I used `font.getFamily()` instead of `font.getFontName()` – Saleh Feek Feb 29 '16 at 14:36