import javax.swing.*; import java.awt.*; import java.awt.event.*; class One extends JFrame { One() { Two b = new Two(); Container c = this.getContentPane(); c.add(b); this.setVisible(true); this.setSize(400, 400); this.setDefaultCloseOperation( 3 ); } public static void main(String[] args) { One a = new One(); } } class Two extends JComponent implements MouseMotionListener { Circle eye; Line line; Two() { this.eye = new Circle( new Point(150, 150), 30 ); this.addMouseMotionListener(this); } public void mouseMoved(MouseEvent e) { int x = e.getX(), y = e.getY(); System.out.println( "(" + x + ", " + y + ")" ); this.line = new Line( this.eye.center, new Point( x, y ) ); this.repaint(); } public void mouseDragged(MouseEvent e) { System.out.println("Mouse dragged..."); } public void paintComponent(Graphics g) { this.eye.draw(g); if (line != null) { this.line.draw(g); this.line.drawPupil(g, this.eye.radius); } } } class Circle { Point center; int radius; Circle(Point c, int r) { this.center = c; this.radius = r; } void draw(Graphics g) { g.drawOval(this.center.x - this.radius, this.center.y - this.radius, this.radius * 2, this.radius * 2); } } class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } double distanceTo(Point another) { int dx = this.x - another.x; int dy = this.y - another.y; return Math.sqrt( dx * dx + dy * dy ); } } class Line { Point a, b; Line(Point a, Point b) { this.a = a; this.b = b; } void draw(Graphics g) { // g.drawLine(a.x, a.y, b.x, b.y); for (int i = 0; i <= 10; i++) { int x, y; double t = (double) i / 10; x = (int) (a.x + t * (b.x - a.x)); y = (int) (a.y + t * (b.y - a.y)); g.fillOval( x-3, y-3, 6, 6 ); } } double length() { return this.a.distanceTo(this.b); } void drawPupil(Graphics g, int r) { int x, y; double t = (double) r / this.length(); x = (int) (a.x + t * (b.x - a.x)); y = (int) (a.y + t * (b.y - a.y)); g.setColor(Color.RED); g.fillOval( x-6, y-6, 12, 12 ); } }