import java.awt.*;
import java.awt.geom.*;
import java.awt.geom.Ellipse2D.Double;
import javax.swing.*;
import java.awt.event.*;
public class oving3stuff extends JApplet{
public static void main (String[]args) {
JFrame frame = new JFrame();
frame.setTitle("Øye");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet applet = new oving3stuff();
applet.init();
frame.getContentPane().add(applet);
frame.pack();
frame.setVisible(true);
}
public void init() {
JPanel panel = new oving3panel();
getContentPane().add(panel);
}
}
class oving3panel extends JPanel implements MouseMotionListener{
private Ellipse2D.Double eye, pupil;
private Point2D.Double eyeCenter, pupilCenter;
private Point mouseHere = new Point();
Point testPoint = new Point(0,0);
private double w, h;
private double oX, oY, x, y;
private double eyeRadius, pupilRadius;
public oving3panel() {
setPreferredSize(new Dimension(640, 480));
setBackground(Color.white);
}
@Override public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
w = this.getWidth(); h = this.getHeight();
oX = w/2; oY = h/2; x = w/20; y = h/20;
eyeCenter = new Point2D.Double(oX, oY);
eyeRadius = x*5;
pupilRadius = x*2;
pupilCenter = getPupilCenterLoc(eyeCenter, mouseHere);
eye = new Ellipse2D.Double(oX-(x*5), oY-(y*5), x*10, y*10);
pupil = new Ellipse2D.Double(pupilCenter.x, pupilCenter.y, pupilRadius, pupilRadius);
g2.drawLine(0, (int)oY, (int)w, (int)oY);
g2.drawLine((int)oX, 0, (int)oX, (int)h);
g2.draw(eye);
g2.draw(pupil);
}
private Point2D.Double getPupilCenterLoc(Point2D.Double eyeCenter, Point mousePoint) {
double x1 = eyeCenter.x;
double y1 = eyeCenter.y;
double mouseX = mousePoint.getX();
double mouseY = mousePoint.getY();
Point2D.Double refPoint = new Point2D.Double(mouseX, mouseY);
double distance = getDistance(eyeCenter, refPoint);
double radius = eyeRadius - pupilRadius;
double x2 = x1 + ((mouseX - x1)*(radius/distance));
double y2 = y1 + ((mouseY - y1)*(radius/distance));
return new Point2D.Double(x2, y2);
}
private double getDistance(Point2D.Double p1, Point2D.Double p2) {
return Math.sqrt(square(p1.x - p2.x) + square(p1.y - p2.y));
}
private double square(double d) {
return d*d;
}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
mouseHere = e.getPoint();
System.out.println(e.getPoint().toString());
repaint();
}
}