| 1 36 37 40 41 package java2d.demos.Fonts; 42 43 44 import static java.awt.Color .*; 45 import java.awt.*; 46 import java.awt.event.*; 47 import java.awt.font.TextLayout ; 48 import java.awt.font.TextHitInfo ; 49 import java.awt.font.FontRenderContext ; 50 import java.awt.geom.Rectangle2D ; 51 import java.awt.geom.AffineTransform ; 52 import java2d.AnimatingSurface; 53 54 55 59 public class Highlighting extends AnimatingSurface { 60 61 private static String text[] = { "HILIGHTING", "Java2D" }; 62 private static Color colors[] = { CYAN, LIGHT_GRAY }; 63 private static Font smallF = new Font("Monospaced", Font.PLAIN, 8); 64 private int[] curPos; 65 private TextLayout [] layouts; 66 private Font[] fonts; 67 68 69 public Highlighting() { 70 setBackground(WHITE); 71 fonts = new Font[2]; 72 layouts = new TextLayout [fonts.length]; 73 curPos = new int[fonts.length]; 74 } 75 76 77 public void reset(int w, int h) { 78 fonts[0] = new Font("Monospaced",Font.PLAIN,w/text[0].length()+8); 79 fonts[1] = new Font("Serif", Font.BOLD,w/text[1].length()); 80 for (int i = 0; i < layouts.length; i++ ) { 81 curPos[i] = 0; 82 } 83 } 84 85 86 public void step(int w, int h) { 87 setSleepAmount(900); 88 for (int i = 0; i < 2; i++) { 89 if (layouts[i] == null) { 90 continue; 91 } 92 if (curPos[i]++ == layouts[i].getCharacterCount()) { 93 curPos[i] = 0; 94 } 95 } 96 } 97 98 99 public void render(int w, int h, Graphics2D g2) { 100 FontRenderContext frc = g2.getFontRenderContext(); 101 for (int i = 0; i < 2; i++) { 102 layouts[i] = new TextLayout (text[i], fonts[i], frc); 103 float rw = layouts[i].getAdvance(); 104 float rh = layouts[i].getAscent() + layouts[i].getDescent(); 105 float rx = (float) ((w - rw) /2); 106 float ry = (float) ((i == 0) ? h/3 : h * 0.75f); 107 108 Shape hilite = layouts[i].getLogicalHighlightShape(0, curPos[i]); 110 AffineTransform at = AffineTransform.getTranslateInstance(rx, ry); 111 hilite = at.createTransformedShape(hilite); 112 float hy = (float) hilite.getBounds2D().getY(); 113 float hh = (float) hilite.getBounds2D().getHeight(); 114 g2.setColor(colors[i]); 115 g2.fill(hilite); 116 117 Shape[] shapes = layouts[i].getCaretShapes(curPos[i]); 119 Shape caret = at.createTransformedShape(shapes[0]); 120 121 g2.setColor(BLACK); 122 layouts[i].draw(g2, rx, ry); 123 g2.draw(caret); 124 g2.draw(new Rectangle2D.Float (rx,hy,rw,hh)); 125 126 for (int j = 0; j <= layouts[i].getCharacterCount(); j++) { 128 float[] cInfo = layouts[i].getCaretInfo(TextHitInfo.leading(j)); 129 String str = String.valueOf((int) cInfo[0]); 130 TextLayout tl = new TextLayout (str,smallF,frc); 131 tl.draw(g2, (float) rx+cInfo[0]-tl.getAdvance()/2, hy+hh+tl.getAscent()+1.0f); 132 } 133 } 134 } 135 136 137 public static void main(String argv[]) { 138 createDemoFrame(new Highlighting()); 139 } 140 } 141 | Popular Tags |