Mega Code Archive

 
Categories / Java by API / Java Text
 

TextAttribute CHAR_REPLACEMENT

import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.font.GraphicAttribute; import java.awt.font.ImageGraphicAttribute; import java.awt.font.TextAttribute; import java.awt.image.BufferedImage; import java.text.AttributedString; import javax.swing.JComponent; import javax.swing.JFrame; public class MainClass {   public static void main(String[] args) {     JFrame jf = new JFrame("Demo");     Container cp = jf.getContentPane();     MyCanvas tl = new MyCanvas();     cp.add(tl);     jf.setSize(300, 200);     jf.setVisible(true);   } } class MyCanvas extends JComponent {   public void paint(Graphics g) {     Graphics2D g2 = (Graphics2D) g;     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);     Font serifFont = new Font("Serif", Font.PLAIN, 32);     AttributedString as = new AttributedString("www.rntsoft.com");     as.addAttribute(TextAttribute.FONT, serifFont);     Image image =  createImage();     ImageGraphicAttribute imageAttribute = new ImageGraphicAttribute(image,         GraphicAttribute.TOP_ALIGNMENT);     as.addAttribute(TextAttribute.CHAR_REPLACEMENT, imageAttribute, 5, 6);     g2.drawString(as.getIterator(), 20, 120);   }   private BufferedImage createImage() {     BufferedImage bim;     Color[] colors = { Color.red, Color.blue, Color.yellow, };     int width = 8, height = 8;     bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);     Graphics2D g2 = bim.createGraphics();     for (int i = 0; i < width; i++) {       g2.setPaint(colors[(i / 2) % colors.length]);       g2.drawLine(0, i, i, 0);       g2.drawLine(width - i, height, width, height - i);     }     return bim;   } }