tags:

views:

435

answers:

2

I'm messing around with DefaultStyledDocument and am trying to figure out the right way to set a style to the proper monospaced font. By "proper" I mean that the font selected is:

  1. A monospaced font that exists on the user's machine
  2. A font specified by the user's preferences (is there a standard way to do this in Java?)
  3. If there is no specified font, it will fall back on the standard monospaced font ("Monospaced").

This works:

StyleConstants.setFontFamily(mainStyle, "Monospaced");

and this also works:

StyleConstants.setFontFamily(mainStyle, "Lucida Console");

but I can't seem to figure out how to tell if the font family in question both exists on the user's machine (there's no return value to setFontFamily) and is a monospaced font. If I use "Lucida Consoleq" it seems to use whatever the default font is.

A: 

I think you want this

GraphicsEnvironment.getAvailableFontFamilyNames()

See javadoc

Joel Carranza
do I have to enumerate all of them? there isn't a way to just test to see if one exists?
Jason S
+1  A: 

See the javadoc for java.awt.Font. It appears you may be able to use the public static Font decode(String str) method to accomplish what you want. The last paragraph of the javadoc for this method says:

The default size is 12 and the default style is PLAIN. If str does not specify a valid size, the returned Font has a size of 12. If str does not specify a valid style, the returned Font has a style of PLAIN. If you do not specify a valid font name in the str argument, this method will return a font with the family name "Dialog". To determine what font family names are available on your system, use the GraphicsEnvironment.getAvailableFontFamilyNames() method. If str is null, a new Font is returned with the family name "Dialog", a size of 12 and a PLAIN style.

If the font family you are looking for does not exist, you will get "Dialog" returned. As long as you do not get that as a return value, the font family exists.

ssakl