在 Swing 中选择等宽字体的正确方法
我正在摆弄 DefaultStyledDocument,并试图找出将样式设置为正确的等宽字体的正确方法。 我所说的“正确”是指选择的字体是:
- 用户计算机上存在的等宽字体
- 由用户首选项指定的字体(在 Java 中是否有标准方法来执行此操作?)
- 如果没有指定的字体,它将依靠标准等宽字体(“Monospaced”)。
这有效:
StyleConstants.setFontFamily(mainStyle, "Monospaced");
这也有效:
StyleConstants.setFontFamily(mainStyle, "Lucida Console");
但我似乎无法弄清楚如何判断所讨论的字体系列是否既存在于用户的计算机上(setFontFamily 没有返回值)并且是等宽字体。 如果我使用“Lucida Consoleq”,它似乎会使用默认字体。
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:
- A monospaced font that exists on the user's machine
- A font specified by the user's preferences (is there a standard way to do this in Java?)
- 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅 javadoc 了解
java.awt.Font
。 看来您可以使用public static Font Decode(String str)
方法来完成您想要的任务。 该方法的 javadoc 最后一段说:如果您要查找的字体系列不存在,您将得到“Dialog”返回。 只要您没有将其作为返回值,字体系列就存在。
See the javadoc for
java.awt.Font
. It appears you may be able to use thepublic static Font decode(String str)
method to accomplish what you want. The last paragraph of the javadoc for this method says: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.
我想你想要这个
请参阅 javadoc
I think you want this
See javadoc
Monospaced
是一个虚拟名称(如Dialog
),Java 将其映射到系统默认的固定宽度字体。Monospaced
is a virtual name (likeDialog
) which Java will map to the default fixed-width font of the system.