/* 
 * Mover.java
 *
 * (C) Copyright 2007, Morten Rhiger
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * March 20, 2007, Morten Rhiger (mir@ruc.dk)
 */

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;

/**
    A small class to illustrate events.
 
    @author    Morten Rhiger (mir@ruc.dk)
    @version   March 20, 2007
*/
public class Mover extends JComponent implements MouseMotionListener {

    private int mouse_x, mouse_y;
    
    /**
        Constructs a new Mover component
    */
    public Mover() {
	/* A Mover is a JComponent (because this class extends the
	   class JComponent).

	   Any JComponent (and therefore also a Mover) contains a set
	   of "listeners".  These are objects that handle events (such
	   a mouse movements, button clicks, etc.), when they happen.

	   Here we instruct this component that it should itself
	   handle events that happen.
	*/
	this.addMouseMotionListener(this);

	mouse_x = 0;
	mouse_y = 0;
    }

    public void paintComponent(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;

	g2.setBackground(Color.WHITE);
	g2.clearRect(0, 0, getWidth(), getHeight());

	Ellipse2D.Double circle = 
	    new Ellipse2D.Double(mouse_x - 10, mouse_y - 10, 20, 20);
	g2.draw(circle);
    }
	    
    public void mouseDragged(MouseEvent e) {
	// Invoked when a mouse button is pressed on a component and
	// then dragged.

	mouse_x = getWidth() - e.getX();
	mouse_y = getHeight() - e.getY();
	repaint();
    }

    public void mouseMoved(MouseEvent e) {
	// Invoked when the mouse cursor has been moved onto a
	// component but no buttons have been pushed.

	mouse_x = e.getX();
	mouse_y = e.getY();
	repaint();
    }

    public static void main(String[] args) {
	JFrame frame = new JFrame();

	frame.setSize(400, 400);
	frame.setTitle("Mover");
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	frame.add(new Mover());

	frame.setVisible(true);
    }
}

