Share on Google+Share on Google+

Adding attributes to the string

Advertisement
In this section, you will learn how to add an attribute to the string.

Adding attributes to the string

In this section, you will learn how to add an attribute to the string.

For holding text and related attribute information, java.text.* package introduces a class AttributedString. This class provides support for marking ranges of characters with an attribute, give different patterns to string. You can change the font and text color of the string through this class. Here, the given example marks a sentence in a string with the attributes font and color.

In the given example, we have created an object of class AttributedString and specified a string inside the constructor of the class. Using the Font and Color class, we have specified the font and color, we want to use as the attributes. The method addAttribute() of AttributedString class add these attributes to the string. Now to display this attributed string on the frame, we have used the method drawString() of Graphics2D.

Grpahics2D:  This class is responsible for coordinate transformations, color management, and text layout.

getIterator(): This method of AttributedString class provides access to the entire contents of this string.

Here is the code:

import java.awt.*;
import java.text.*;
import javax.swing.*;
import java.awt.font.*;

public class AddAttributeExample extends JPanel {
	public void paint(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		String text = "All glitters are not gold.";
		Font font = new Font("Book Antiqua", Font.PLAIN, 30);
		AttributedString attributedString = new AttributedString(text);
		attributedString.addAttribute(TextAttribute.FONT, font);
		attributedString.addAttribute(TextAttribute.FOREGROUND, Color.red);
		g2d.drawString(attributedString.getIterator(), 40, 80);
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame("Add Attribute");
		frame.getContentPane().add(new AddAttributeExample());
		frame.setSize(400, 150);
		frame.setVisible(true);
	}
}

Output:

Advertisements

Posted on: April 3, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.