Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Java Tutor

Java Tutor is my platform for teaching about Java 7+ and JavaFX 2.0+, mainly via programming projects.


Attributed Strings

 

An attributed string is a string that's associated with attributes (style information, such as colors, underlining, and so on). Attributed strings are useful in code editors (to achieve syntax highlighting, for example), HTML page viewers, and other contexts.

Attributed strings are implemented as instances of the java.text.AttributedString class. Each AttributedString instance encapsulates a string's characters with a set of attributes that apply to the entire string or a substring.

AttributedString provides several constructors for initializing class instances. The simplest constructor is AttributedString(String text), which initializes the AttributedString instance to the characters located in text, and which is demonstrated below:

AttributedString as;
as = new AttributedString("An AttributedString holds text and related attribute information.");

This constructor initializes the AttributedString instance to the An AttributedString holds text and related attribute information. character sequence. No attributes are initially associated with this text.

Note: AttributedString(String text) throws NullPointerException whan a null reference is passed to text.

Once you've created an AttributedString instance, you'll want to associate attributes with the entire string or with a substring. You can accomplish these tasks by calling the following pair of addAttribute() methods:

  • void addAttribute(AttributedCharacterIterator.Attribute attribute, Object value) associates attribute and value with the entire string.
  • void addAttribute(AttributedCharacterIterator.Attribute attribute, Object value, int beginIndex, int endIndex) associates attribute and value with the substring ranging from beginIndex to endIndex-1.

Each attribute consists of a key and a value. The key is an instance of the java.text.AttributedCharacterIterator.Attribute class or a subclass (such as java.awt.font.TextAttribute). The value is an arbitrary object whose type agrees with the key.

Note: AttributedCharacterIterator.Attribute defines attribute keys for identifying text attributes. Its java.awt.font.TextAttribute subclass defines attribute keys and values for use in text rendering.

The following code fragment extends the previous code fragment and demonstrates the second addAttribute() method:

as.addAttribute(TextAttribute.FONT, new Font("Courier New", Font.BOLD, 12), 3, 19); 
as.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 3, 19);

The first method call associates the 12-point/bold/Courier New font with the sequence of characters ranging from index 3 through index 18. It uses TextAttribute.FONT as this attribute's key, and requires a java.awt.Font object to be specified as the attribute's value.

The second method call associates color blue with the same sequence of characters. It uses TextAttribute.FOREGROUND as this attribute's key, and requires a java.awt.Paint object (such as a java.awt.Color instance) to be specified as the attribute's value.

The java.awt.Graphics2D class provides a pair of drawString() methods for rendering an attributed string:

  • void drawString(AttributedCharacterIterator iterator, float x, float y)
  • void drawString(AttributedCharacterIterator iterator, int x, int y)

Instead of accepting an AttributedString instance, each drawString() method requires an AttributedCharacterIterator instance. This requirement lets developers choose their own storage models for text and attributes.

The following code fragment continues on from the previous code fragment by obtaining an iterator (via AttributedString's AttributedCharacterIterator getIterator() method) and calling the second drawString() method to render the attributed string:

g.drawString(as.getIterator(), 30, 30);

Listing 1 presents the source code to an applet that combines these code fragments into a working demonstration of AttributedString.

// AttribStringDemo.java

import java.applet.Applet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import java.awt.font.TextAttribute;

import java.text.AttributedString;

public class AttribStringDemo extends Applet
{
   AttributedString as;

   public void init()
   {
      as = new AttributedString("An AttributedString holds text and related "+
                                "attribute information.");
      as.addAttribute(TextAttribute.FONT,
                      new Font("Courier New", Font.BOLD, 12), 3, 19);
      as.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 3, 19);
   }

   public void paint(Graphics g)
   {
      if (as != null)
      {
         ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                           RenderingHints.VALUE_ANTIALIAS_ON);
         g.drawString(as.getIterator(), 30, 30);
      }
   }
}

Listing 1: AttribStringDemo.java

Listing 1's paint(Graphics) method first enables antialiasing (by executing setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)) so that the resulting text (see Figure 1) looks smooth.

Figure 1: The drawString() method renders AttributedString in its own font and color.

Exercises

  1. What is an attributed string?
  2. Identify the class whose instances describe attributed strings.
  3. What method of the class that describes attributed strings do you call to associate an attribute with a substring?
  4. Why does drawString() require an AttributedCharacterInstance argument?
  5. What is the purpose of the AttributedString(String text, Map<? extends AttributedCharacterIterator.Attribute, ?> attributes) constructor? Under what circumstance would this constructor throw IllegalArgumentException?

Code

You can download this post's code and answers here. Code was developed and tested with JDK 7u2 on a Windows XP SP3 platform.

* * *

I welcome your input to this blog, and will write about relevant topics that you suggest. While waiting for the next blog post, check out my TutorTutor website to learn more about Java and other computer technologies (and that's just the beginning).