// MouseApplicationAnonAdapter.java: GUI Application to move a 
//  rectangle around a panel via mouse clicks
// Employs an anon adapter

// Written for ICS 45J by Norman Jacobson, August 2012
// Adapted from MouseApplicationAnonAdapter.java and MouseApplet0.java
//  from ICS 21 3/09 versions

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MouseApplicationAnonAdapter
{
	public static void main(String[] args)
	{
		// Make a panel with the rectangle in it
		RectanglePanel rectPanel = new RectanglePanel();

		// Make a frame that
		// ...closes on exit
		// ...has rectPanel as its content pane (pane that holds all the UI components)
		// ...pack it so the frame is just the right size to hold the rectangle panel
		// Then display the pane
		JFrame appFrame = new JFrame();
		appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		appFrame.setContentPane(rectPanel);
		appFrame.pack();
		appFrame.setVisible(true);
	}

}

// Make and paint a panel that contains a rectangle
class RectanglePanel extends JPanel
{
	private Rectangle box;

	public RectanglePanel()
	{	// Add to the mouse listener 
		// an anonymous object that reacts
		// to a mouse press by updating the
		// location of, and redrawing, the
		// rectangle
		addMouseListener(
			new MouseAdapter()
			{
				public void mousePressed(MouseEvent event)
				{
					int x = event.getX();
					int y = event.getY();
					box.setLocation(x,y);
					repaint();
				}
			}
		);
		setPreferredSize(new Dimension(300,300));
		box = new Rectangle(100,100,20,30);
	}

	// repaint the rectangle
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		g2.draw(box);
	}
}