659.md 1.6 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8
# 使用文本属性来设置文本样式

> 原文: [https://docs.oracle.com/javase/tutorial/2d/text/textattributes.html](https://docs.oracle.com/javase/tutorial/2d/text/textattributes.html)

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

*   _ 下划线 _ - 在文本下面绘制的一条线
*   _ 删除线 _ - 通过文本绘制的水平线
W
wizardforcel 已提交
9
*   _ 上标*或*下标 _ - 略高于一行或相应低于一行的文字或字母
W
init  
wizardforcel 已提交
10 11 12 13 14 15
*   _ 字距 _ - 调整字符间距

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

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

W
wizardforcel 已提交
16
```java
W
init  
wizardforcel 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
Map<TextAttribute, Object> map =
    new Hashtable<TextAttribute, Object>();
map.put(TextAttribute.KERNING,
    TextAttribute.KERNING_ON);
font = font.deriveFont(map);
graphics.setFont(font);

```

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

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

&lt;applet alt="AttributedText applet" archive="examples/lib/AttributedTextApplet.jar" code="AttributedText" height="250" width="300"&gt;&lt;param name="permissions" value="sandbox"&gt;&lt;/applet&gt;

* * *

**Note:**  If you don't see the applet running, you need to install at least the [Java SE Development Kit (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/index.html) release.

* * *

该 applet 的完整代码位于 [`AttributedText.java`](examples/AttributedText.java) 中。