Switch to full style
General Java code examples
Post a reply

Different Strokes

Tue Nov 11, 2008 8:34 pm

draw Different Strokes in java
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.event.*;

public class ShowDifferentStrokes extends JPanel{
  Stroke[] stroke = new Stroke[] { new BasicStroke(3.0f),
     new Stroke1(7.0f, 1.0f), new Stroke2(2.0f) };

  public void paint(Graphics g1) {
    Graphics2D g2d = (Graphics2D)g1;
    Font font = new Font("Arial Narrow", Font.BOLD, 40);
    GlyphVector glyphVector = font.createGlyphVector
              (g2d.getFontRenderContext(), "HELLO");
    Shape shape = glyphVector.getOutline();
  g2d.setColor(Color.red);
    g2d.translate(10, 175);


  for (int i = 0; i < stroke.length; i++) {
      g2d.setStroke(stroke[i]);
      g2d.draw(shape);
      g2d.translate(140, 0);
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("Show Different Strokes");
    frame.setContentPane(new ShowDifferentStrokes());
    frame.setSize(450,300);
    frame.show();
  }
}
class Stroke1 implements Stroke {
  BasicStroke basicStroke1, basicStroke2;
  public Stroke1(float w1, float w2) {
    basicStroke1 = new BasicStroke(w1);
    basicStroke2 = new BasicStroke(w2);
  }
public Shape createStrokedShape(Shape sh) {
    Shape shape = basicStroke1.createStrokedShape(sh);
    return basicStroke2.createStrokedShape(shape);
  }
}
class Stroke2 implements Stroke {
  float radius;
  public Stroke2(float radius) {
  this.radius = radius;
  }
  public Shape createStrokedShape(Shape sh) {
    GeneralPath path = new GeneralPath(new BasicStroke(1.0f)
        .createStrokedShape(sh));
    float[] fl = new float[6];
    for (PathIterator iterator = sh.getPathIterator(null);
     !iterator.isDone();iterator.next()) {
      int type = iterator.currentSegment(fl);
      switch (type) {
      case PathIterator.SEG_CUBICTO:
      coordinate1(path, fl[4], fl[5]);
      case PathIterator.SEG_QUADTO:
      coordinate1(path, fl[2], fl[3]);
      case PathIterator.SEG_MOVETO:
      case PathIterator.SEG_LINETO:
      coordinate1(path, fl[0], fl[1]);
      case PathIterator.SEG_CLOSE:
      break;
      }
    }
   return path;
  }
  void coordinate1(GeneralPath path, float x, float y) {
    path.moveTo(x - radius, y - radius);
    path.lineTo(x + radius, y - radius);
    path.lineTo(x + radius, y + radius);
    path.lineTo(x - radius, y + radius);
    path.closePath();
  }
}



Attachments
differentStrokes.gif
Java Different Strokes
differentStrokes.gif (7.8 KiB) Viewed 4264 times

Post a reply

Topic Tags

Java Graphics