AttributedString Example
An AttributedString string is rendered. The class AttributedString constructs a string and provides methods to provide attributes to defined parts of it.
In this example we (1) set a font for the whole string, (2) set a different font for one word of it using the indexes of the where the word starts and ends, and (3) using the same indexes change the color of that same word in the string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// AttributedString Example
import java.awt.*;
import javax.swing.*;
import java.text.*;
import java.awt.font.TextAttribute;
class AttributedStringExample extends JApplet {
@Override public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
String s = "my WORST moment";
Font f0 = new Font("SansSerif", Font.PLAIN, 18);
Font f1 = new Font("Serif", Font.BOLD+Font.ITALIC, 24);
AttributedString as = new AttributedString(s);
as.addAttribute(TextAttribute.FONT, f0);
as.addAttribute(TextAttribute.FONT, f1, 3, 8);
as.addAttribute(TextAttribute.FOREGROUND, Color.red, 3, 8);
g2.drawString(as.getIterator(), 30, 150);
}
}
18 The AttributedString is constructed.
19 The whole string is given a font using the method AttributedString.addAttribute() with parameter TextAttribute.FONT.
20 One word of the string (between indexes 3 and 8) is given a font using the method AttributedString.addAttribute() with parameter TextAttribute.FONT.
21 The same word of the string is given a foreground color using the method AttributedString.addAttribute() with parameter TextAttribute.FOREGROUND.
