A demo program written by Roger
mport java.awt.*;
import javax.swing.*;
public class Test101 extends JFrame
{
public Test101()
{
super("Test 101");
this.getContentPane().setLayout(new BorderLayout());
MyCanvas canvas = new MyCanvas();
this.getContentPane().add(canvas, BorderLayout.CENTER);
this.setSize(700, 700);
}
class MyCanvas extends JPanel
{
Point pt1 = new Point(10, 20);
Point pt2 = new Point(200, 400);
double r = 300;
public void paintComponent(Graphics g)
{
g.translate(200, 100);
g.setColor(Color.red);
g.drawLine(pt1.x, pt1.y, pt2.x, pt2.y);
g.setColor(Color.blue);
for (double theta = 0.0; theta <2.0*Math.PI; theta += 0.11)
{
Point p = new Point((int)(Math.sin(theta)*r+0.5)+100, (int)(Math.cos(theta)*r+0.5)+200);
Point q = myGetClosestPoint(pt2, pt1, p);
g.drawLine(q.x, q.y, p.x, p.y);
}
}
}
public static void main(
String[] args)
{
new Test101().setVisible(true);
}
private static Point myGetClosestPoint(Point pt1, Point pt2, Point p)
{
double u = ((p.x-pt1.x)*(pt2.x-pt1.x)+(p.y-pt1.y)*(pt2.y-pt1.y))/(sqr(pt2.x-pt1.x)+sqr(pt2.y-pt1.y));
if (u > 1.0)
return (Point)pt2.clone();
else if (u <= 0.0)
return (Point)pt1.clone();
else
return new Point((int)(pt2.x*u+pt1.x*(1.0-u)+0.5), (int)(pt2.y*u+pt1.y*(1.0-u)+0.5));
}
private static double sqr(double x)
{
return x*x;
}
}