1 43 package org.jfree.demo; 44 45 import java.awt.Color ; 46 import java.awt.Dimension ; 47 import java.awt.Font ; 48 import java.awt.Graphics ; 49 import java.awt.Graphics2D ; 50 import java.awt.Insets ; 51 import java.awt.geom.Line2D ; 52 import java.awt.geom.Rectangle2D ; 53 54 import javax.swing.JPanel ; 55 56 import org.jfree.text.TextUtilities; 57 import org.jfree.ui.TextAnchor; 58 59 64 public class DrawStringPanel extends JPanel { 65 66 67 private static final Dimension PREFERRED_SIZE = new Dimension (500, 300); 68 69 70 private boolean rotate; 71 72 73 private String text = "Hello World"; 74 75 76 private TextAnchor anchor = TextAnchor.TOP_LEFT; 77 78 79 private TextAnchor rotationAnchor = TextAnchor.TOP_LEFT; 80 81 82 private Font font = new Font ("Serif", Font.PLAIN, 12); 83 84 85 private double angle; 86 87 93 public DrawStringPanel(final String text, final boolean rotate) { 94 this.text = text; 95 this.rotate = rotate; 96 } 97 98 103 public Dimension getPreferredSize() { 104 return PREFERRED_SIZE; 105 } 106 107 112 public void setAnchor(final TextAnchor anchor) { 113 this.anchor = anchor; 114 } 115 116 121 public void setRotationAnchor(final TextAnchor anchor) { 122 this.rotationAnchor = anchor; 123 } 124 125 130 public void setAngle(final double angle) { 131 this.angle = angle; 132 } 133 134 139 public Font getFont() { 140 return this.font; 141 } 142 143 148 public void setFont(final Font font) { 149 this.font = font; 150 } 151 152 157 public void paintComponent(final Graphics g) { 158 159 super.paintComponent(g); 160 final Graphics2D g2 = (Graphics2D ) g; 161 162 final Dimension size = getSize(); 163 final Insets insets = getInsets(); 164 final Rectangle2D available = new Rectangle2D.Double ( 165 insets.left, insets.top, 166 size.getWidth() - insets.left - insets.right, 167 size.getHeight() - insets.top - insets.bottom 168 ); 169 170 final double x = available.getCenterX(); 171 final double y = available.getCenterY(); 172 173 final Line2D line1 = new Line2D.Double (x - 2.0, y + 2.0, x + 2.0, y - 2.0); 174 final Line2D line2 = new Line2D.Double (x - 2.0, y - 2.0, x + 2.0, y + 2.0); 175 g2.setPaint(Color.red); 176 g2.draw(line1); 177 g2.draw(line2); 178 179 g2.setFont(this.font); 180 g2.setPaint(Color.black); 181 if (this.rotate) { 182 TextUtilities.drawRotatedString( 183 this.text, g2, (float) x, (float) y, 184 this.anchor, this.angle, this.rotationAnchor 185 ); 186 } 187 else { 188 TextUtilities.drawAlignedString(this.text, g2, (float) x, (float) y, this.anchor); 189 } 190 191 } 192 193 } 194 | Popular Tags |