Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the right way to select monospaced fonts in Swing

Tags:

java

fonts

swing

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.

like image 878
Jason S Avatar asked Apr 06 '09 15:04

Jason S


2 Answers

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.

like image 79
ssakl Avatar answered Sep 20 '22 11:09

ssakl


Monospaced is a virtual name (like Dialog) which Java will map to the default fixed-width font of the system.

like image 40
Aaron Digulla Avatar answered Sep 18 '22 11:09

Aaron Digulla