Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java: How to change the attributes (color and font) of a portion of text using ‘AttributedString’ class

Java: How to change the attributes (color and font) of a portion of text using 'AttributedString' class
{filelink=9436}

  import java.awt.*;
  import java.awt.font.TextAttribute;
  import java.text.*;
  import javax.swing.*;
/*
 *  Draw text and change
 *  its font and color
 */
  public class AttributsText
		{
		 public static void main(String[] args)
		 {
		   JFrame f = new JFrame("Texts Attributes - Font et Color")
		   {
				public void paint(Graphics g)
				{
				Graphics2D g2 = (Graphics2D)g;
				String texte = "Exemples Java";
				Dimension d = getSize();
				g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
	// Create two fonts
				Font font1 = new Font("Serif", Font.PLAIN, 48);
				Font font2 = new Font("Monospaced", Font.PLAIN, 48);
				AttributedString str_attribut = new AttributedString(texte);
	// Apply the fonts to the text
				str_attribut.addAttribute(TextAttribute.FONT, font1);
// Edit charactere font from index 2 to 7
				str_attribut.addAttribute(TextAttribute.FONT, font2, 2, 7);
				// Edit charactere color from index 2 to 7
				str_attribut.addAttribute(TextAttribute.FOREGROUND, Color.red, 2, 7);
				g2.drawString(str_attribut.getIterator(), 40, 80);
				}
		};
		f.setSize(400,150);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setLocationRelativeTo(null);
		f.setVisible(true);
	   }
}

Users who found this page were searching for:

  • java attributed string change text color
  • java attributedstring change color
  • java how to change font attributes
  • java expression to change font color
  • java AttributedString retreive font
  • swing AttributedString image
  • set font color attributedstring in swing
  • change color for underline in attributedString
  • java attributedstring examples
  • java font monospaced attributes

No comments yet.

Leave a Comment