import java.awt.geom.*; import java.awt.*; class SpringView { private static final double xPoints[]={0,0.10, 0.125, 0.175, 0.225, 0.275, 0.325, 0.375, 0.425, 0.475, 0.525,0.575,0.625, 0.675,0.725,0.775,0.825,0.875, 0.90,1.0}; private static final double yPoints[]={0,0,-0.05,0.05,-0.05,0.05,-0.05,0.05,-0.05,0.05, -0.05,0.05,-0.05,0.05,-0.05,0.05,-0.05,0.05,0,0}; private static final Path2D.Double polyline = new Path2D.Double(Path2D.WIND_EVEN_ODD,xPoints.length); private Stroke stroke; private Spring spring; static { // static initialization block. It creates a spring of length = 1. polyline.moveTo (xPoints[0], yPoints[0]); for (int index = 1; index < xPoints.length;index++) polyline.lineTo(xPoints[index], yPoints[index]); } public SpringView(Spring spring) { this.spring = spring; AffineTransform at = AffineTransform.getTranslateInstance(0,0); stroke = new BasicStroke(0.01f); } public Vector2D getAendPosition() { return spring.getAendPosition(); } public Vector2D getBendPosition() { return spring.getBendPosition(); } public void paint (Graphics2D g){ Vector2D a=spring.getAendPosition(); double restLength = spring.getRestLength(); double ax = a.getX(); double ay = a.getY(); Vector2D v = spring.getBendPosition().minus(a); AffineTransform at = AffineTransform.getTranslateInstance(ax, ay); at.rotate(v.getX(), v.getY()); at.scale(v.module(), restLength); Path2D.Double shape = (Path2D.Double) at.createTransformedShape(polyline); if (v.module() < restLength) g.setColor(Color.BLACK); else g.setColor(Color.RED); g.setStroke(stroke); g.draw(shape); } }