001package horstmann.ch08_graphed; 002import java.awt.Color; 003import java.awt.Graphics2D; 004import java.awt.geom.Ellipse2D; 005import java.awt.geom.Point2D; 006import java.awt.geom.Rectangle2D; 007 008/** 009 A circular node that is filled with a color. 010 */ 011@SuppressWarnings("serial") 012public class CircleNode implements Node 013{ 014 /** 015 Construct a circle node with a given size and color. 016 @param aColor the fill color 017 */ 018 public CircleNode(Color aColor) 019 { 020 size = DEFAULT_SIZE; 021 x = 0; 022 y = 0; 023 color = aColor; 024 } 025 026 public Object clone() 027 { 028 try 029 { 030 return super.clone(); 031 } 032 catch (CloneNotSupportedException exception) 033 { 034 return null; 035 } 036 } 037 038 public void draw(Graphics2D g2) 039 { 040 Ellipse2D circle = new Ellipse2D.Double( 041 x, y, size, size); 042 Color oldColor = g2.getColor(); 043 g2.setColor(color); 044 g2.fill(circle); 045 g2.setColor(oldColor); 046 g2.draw(circle); 047 } 048 049 public void translate(double dx, double dy) 050 { 051 x += dx; 052 y += dy; 053 } 054 055 public boolean contains(Point2D p) 056 { 057 Ellipse2D circle = new Ellipse2D.Double( 058 x, y, size, size); 059 return circle.contains(p); 060 } 061 062 public Rectangle2D getBounds() 063 { 064 return new Rectangle2D.Double( 065 x, y, size, size); 066 } 067 068 public Point2D getConnectionPoint(Point2D other) 069 { 070 double centerX = x + size / 2; 071 double centerY = y + size / 2; 072 double dx = other.getX() - centerX; 073 double dy = other.getY() - centerY; 074 double distance = Math.sqrt(dx * dx + dy * dy); 075 if (distance == 0) return other; 076 else return new Point2D.Double( 077 centerX + dx * (size / 2) / distance, 078 centerY + dy * (size / 2) / distance); 079 } 080 081 private double x; 082 private double y; 083 private double size; 084 private Color color; 085 private static final int DEFAULT_SIZE = 20; 086}