I’m using g.drawString(str, x, y) to draw a String with a Graphics2D object g. The current font of g does not cover all the characters of str (I have e.g. Chinese chars in there). On Mac OS X, a fallback font seems to be automatically used, but not on Windows, where black square outlines appear instead of the wanted characters.
- Why is the behavior different depending on the platform?
- How do I specify a fallback font (or several fallback fonts) in case of missing characters?
(For instance, one of the nice fonts there.)
Update/More Info
So, the original font that doesn’t support all characters is not one of the JVM’s logical fonts, but is a bundled font that comes with my app and was obtained with Font.createFont(). So, adding fonts to the JRE’s lib/fonts/fallback folder doesn’t work here.
We could attribute string to switch font on “bad” symbols and use
Graphics2D.drawString(AttributedCharacterIterator iterator, int x, int y)to render result. Advantage: this will work with any font. Drawback: without some sort of caching of intermediate objects this will work slower and dirtier.So, i suggest using
AttributedStringwith main font attribute on whole string:and with fallback font on specific parts:
The rendering itself:
The result (Physical “Segoe Print” as main font, logical “Serif” as fallback):
Complete supposed-to-be-SSCCE code: