使用文本属性来设置文本样式

原文: https://docs.oracle.com/javase/tutorial/2d/text/textattributes.html

应用程序通常需要能够应用以下文本属性:

  • 下划线 - 在文本下面绘制的一条线
  • 删除线 - 通过文本绘制的水平线
  • 上标下标 - 略高于一行或相应低于一行的文字或字母
  • 字距 - 调整字符间距

可以使用 Java 2D TextAttribute类应用这些和其他文本属性。

要通过将这些文本属性添加到Font对象来应用它们。例如:

  1. Map<TextAttribute, Object> map =
  2. new Hashtable<TextAttribute, Object>();
  3. map.put(TextAttribute.KERNING,
  4. TextAttribute.KERNING_ON);
  5. font = font.deriveFont(map);
  6. graphics.setFont(font);

下面显示的代码示例按以下顺序显示了文本属性的应用:

  1. 示例字符串(未应用文本属性)
  2. 字距
  3. 字距和下划线
  4. Kerning,Underlining 和 Strikethrough
  5. 字距,下划线,删除线和颜色

<applet alt=”AttributedText applet” archive=”examples/lib/AttributedTextApplet.jar” code=”AttributedText” height=”250” width=”300”><param name=”permissions” value=”sandbox”></applet>


Note: If you don’t see the applet running, you need to install at least the Java SE Development Kit (JDK) 7 release.


该 applet 的完整代码位于 AttributedText.java 中。