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

  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();
	// 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);

Users who found this page were searching for:

  • change color for underline in attributedString
  • java attributedstring change color
  • change text color String java attributte
  • java attributed string change text color
  • java attributedstring examples
  • java color font example
  • swing AttributedString image
  • java set attributed string color and font
  • java expression to change font color
  • java font monospaced attributes

No comments yet.

Leave a Comment