import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.*;

public class HelloWorld extends JFrame {

    private MyPanel o_panel;

    public HelloWorld() {


	/*
	 * The constructor first called the superclass (JFrame) constructor 
	 * with a string to be used in the title bar of the window.
	 */
	super("HelloWorld");

	/* Now create a panel and set its size */
	o_panel = new MyPanel();
	o_panel.setPreferredSize( new Dimension(200,200) );


	/* Make a listener to listen to mouse events and add it to the panel.
	 * We use the same listener to listen for clicks and drags as we want
	 * to do the same thing in both cases.
	 */
	MouseInputAdapter x_listener = new MyMouseInputAdapter();

	o_panel.addMouseListener( x_listener );
	o_panel.addMouseMotionListener( x_listener );


	/* add the panel to the frame's content pane. */ 
	getContentPane().add( o_panel );

	
	/* Always do these three things when you make a new frame.
	 * They make sure stuff gets displayed!
	 */
	pack();
	setVisible(true);
	show();
    }


    /*
     * getGraphics() returns the Graphics object for the panel, and lets
     * us draw on it. Graphics has lots of methods that let us draw 
     * different shapes. Here we draw a filled rectangle.
     */
    private void drawBox( int p_x , int p_y ) {
	
	o_panel.getGraphics().fillRect( p_x - 10 , p_y , 20 , 20 ) ;
    }


    /*
      All the main method does is to create a HelloWorld object.
     */
    public static void main( String[] args ) {

	HelloWorld x_hw = new HelloWorld();
    }


    /*
     * This is an inner class of HelloWorld, so any methods defined in this 
     * class can call any of the methods defined in HelloWorld. Here 
     * mouseClicked and mouseDragged both call drawBox() which is a method 
     * of HelloWorld. 
     */
    class MyMouseInputAdapter extends MouseInputAdapter {
	
	public void mouseClicked( MouseEvent p_me ) {
	
	    /* Get the x and y coordinates of the mouse click
	       and draw a box there
	     */
	    drawBox( p_me.getX() , p_me.getY() );
	}
	
	public void mouseDragged( MouseEvent p_me ) {
		    
	    drawBox( p_me.getX() , p_me.getY() );
	}
    }    
}


/*
 * This class extends JPanel, giving it the behaviour that it paints 
 * a white background to fill the panel.
 */
class MyPanel extends JPanel {

    MyPanel() {}

    public void paintComponent( Graphics g ) {

	//Make background white
	g.setColor(Color.white);
	g.fillRect(0, 0, getSize().width -1, getSize().height -1);
	g.setColor(Color.black);
    }
}