3

My installation of OS X 10.8 comes pre-installed with 11 fonts in the family Helvetica Neue. I'm trying to find a way to access the fonts with styles like medium or condensed, which cannot be represented by the bit-mask values Font.BOLD and Font.ITALIC.

GraphicsEnvironment.getAllFonts() returns Font objects for all these fonts but applying them using JLabel.setFont() seems to only use the styles representable with the mentioned bit-mask. This is shown on the left in the screenshot below, which compares it to a sample of all fonts when they are used in TextEdit.

The same happens if a Font object is constructed using the font's full name or its PostScript name.

Is there a way to use all those fonts, either by applying it to a Swing component or when painting to a Graphics2D (or Graphics) instance?

Output from the Swing application on the left, sample of all fonts on the right.

Below is the code I used to produce the dialog in the above screenshot.

package fahrplan;

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

public class FontsMain {
    public static void main(String[] a) {
        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));

        for (Font i : e.getAllFonts()) {
            String name = i.getFontName();

            if (name.startsWith("HelveticaNeue")) {
                JLabel label = new JLabel(name);

                label.setFont(i.deriveFont(18f));

                contentPane.add(label);
            }
        }

        JFrame frame = new JFrame("Fonts");
        frame.setContentPane(contentPane);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}
Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
Feuermurmel
  • 8,632
  • 9
  • 52
  • 87

1 Answers1

0

I would do it like this.

int size=12, style=0;

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
final Font[] fonts = e.getAllFonts();
for(int i=0; i<fonts.length; i++)
    {
        JLabel label = new JLabel(Font[i].getName);
        label.setFont(new Font(Font[i].getName, size, style));
        contentPane.add(label);
    }

I hope this helps.

Hullu2000
  • 251
  • 3
  • 19
  • The only difference in your code that I can spot right now is that you use a font size of 12 pt instead of 18. I don't think that's making a difference. ;) On a second note, did you look at the screenshot in my question? – Feuermurmel Mar 22 '13 at 15:55
  • I believe you! I since found out that this only happens for fonts for which multiple styles are stored in the same `.dfont` file, which us unique the OS X. I'm still looking for a way to use all those styles on a Mac. – Feuermurmel Apr 02 '13 at 12:21