You can use an AttributedString and its AttributedCharacterIterator.
Here's an example from "Java 2D Graphics" by Jonathan Knudsen:
import java.awt.*;
import java.awt.font.TextAttribute;
import java.text.*;
public class IteratorTest {
public static void main(String[] args) {
Frame f = new ApplicationFrame("IteratorTest") {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
String s = "a big surprise";
Dimension d = getSize();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font serifFont = new Font("Serif", Font.PLAIN, 48);
Font sansSerifFont = new Font("Monospaced", Font.PLAIN, 48);
AttributedString as = new AttributedString(s);
as.addAttribute(TextAttribute.FONT, serifFont);
as.addAttribute(TextAttribute.FONT, sansSerifFont, 2, 5);
as.addAttribute(TextAttribute.FOREGROUND, Color.red, 2, 5);
g2.drawString(as.getIterator(), 40, 80);
}
};
f.setVisible(true);
}
}
Here is ApplicationFrame:
import java.awt.*
import java.awt.event.*;
public class ApplicationFrame extends Frame {
public ApplicationFrame() {
this("ApplicationFrame v1.0");
}
public ApplicationFrame(String title) {
super(title);
createUI();
}
protected void createUI() {
setSize(600, 400);
center();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
System.exit(0);
}
});
}
public void center() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = getSize();
int x = (screenSize.width - frameSize.width) / 2;
int y = (screenSize.height - frameSize.height) / 2;
setLocation(x, y);
}
}
Please excuse any typos, but this does exactly what you describe. Good luck.
It's a good book, by the way (O'Reilly).
-Erik