TextIcon.java

Go to the documentation of this file.
00001 import javax.swing.*; 00002 import java.awt.*; 00003 import java.awt.font.*; 00004 import java.awt.geom.*; 00005 00008 public class TextIcon implements Icon { 00009 String text = null; 00010 boolean border = true; 00011 Font font = null; 00012 FontRenderContext fontRenderContext = null; 00013 Color color = Color.black; 00014 00015 boolean initialized = false; 00016 int width = -1; 00017 int height = -1; 00018 00025 public TextIcon(String _text, Component c) { 00026 setText(_text); 00027 setFontRenderContext(c); 00028 }; 00029 00038 public TextIcon(String _text, Component c, Color col) { 00039 setText(_text); 00040 setFontRenderContext(c); 00041 setColor(col); 00042 }; 00043 00047 public void setColor(Color col) { 00048 color = col; }; 00051 public Color getColor() { return color; }; 00052 00057 public void setText(String _text) { 00058 checkChange(); 00059 text = _text; }; 00063 public String getText() { return text; }; 00064 00069 public void setFontRenderContext(FontRenderContext frc) { 00070 checkChange(); 00071 fontRenderContext = frc; }; 00077 public void setFontRenderContext(Component c) { 00078 setFontRenderContext(((Graphics2D)c.getGraphics()).getFontRenderContext()); }; 00082 public FontRenderContext getFontRenderContext() { 00083 return fontRenderContext; }; 00084 00091 private void checkChange() { 00092 if (initialized) 00093 throw new UnsupportedOperationException 00094 ("Cannot change Icon's parameters after displaying"); 00095 } 00096 00100 private void init() { 00101 if (initialized) return; 00102 if (font==null) font = new Font("Dialog",Font.PLAIN,10); 00103 if (fontRenderContext==null) 00104 throw new IllegalArgumentException("Need FontRenderContext"); 00105 if (text==null) text = ":)"; 00106 Rectangle2D bounds = 00107 font.getStringBounds(text,fontRenderContext); 00108 //System.out.println("Bounds: "+bounds); 00109 width = (int)(bounds.getWidth()+bounds.getX()+6); 00110 height = (int)(bounds.getHeight()+bounds.getY()+10); 00111 initialized = true; 00112 } 00113 00117 public void paintIcon(Component c, Graphics g, int x, int y) { 00118 init(); 00119 try { 00120 //System.out.println("paint("+x+","+y+")"); 00121 g.setColor(color); 00122 if (border) 00123 g.drawRect(x+1,y+1,width-3,height-2); 00124 g.setFont(font); 00125 g.drawString(text,x+3,y+height-3); 00126 } catch (Throwable e) { 00127 e.printStackTrace(); 00128 } 00129 } 00130 00135 public int getIconWidth() { 00136 init(); 00137 return width; 00138 } 00139 00144 public int getIconHeight() { 00145 init(); 00146 return height; 00147 } 00148 }

Generated on Sun Aug 15 11:56:53 2004 for International Input by doxygen 1.3.7