// Exercise 12.14 Solution

// Draw.java

// Program draws a rectangle with the mouse

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;



public class Draw extends JFrame {

   private int topX, topY;

   private int width, height;

   private int bottomX, bottomY;

   protected JLabel status;



   public Draw()

   {

      super( "Draw" );

      topX = topY = 0;

      addMouseListener( new MouseHandler( this ) );



      status = new JLabel();

      getContentPane().add( status, BorderLayout.SOUTH );

      setSize( 300, 150 );

      show();

   }



   public int getTopX() { return topX; }

   public int getTopY() { return topY; }

   public int getWidth() { return width; }

   public int getHeight() { return height; }

   public int getBottomX() { return bottomX; }

   public int getBottomY() { return bottomY; }

   public void setTopX( int x ) { topX = x; }

   public void setTopY( int y ) { topY = y; }

   public void setBottomX( int x ) { bottomX = x; }

   public void setBottomY( int y ) { bottomY = y; }

   public void setWidth( int w ) { width = w; }

   public void setHeight( int h ) { height = h; }



   public void paint( Graphics g )

   {

      g.drawRect( topX, topY, width, height );

   }



   public static void main( String args[] )

   {

      Draw app = new Draw();

      app.addWindowListener(

         new WindowAdapter() {

            public void windowClosing( WindowEvent e )

            {

               System.exit( 0 );

            }

         }

      );

   }

}



class MouseHandler extends MouseAdapter {

   private Draw draw;



   public MouseHandler( Draw d ) { draw = d; }



   public void mouseReleased( MouseEvent e )

   {

      draw.setBottomX( e.getX() );

      draw.setBottomY( e.getY() );

      draw.setWidth( Math.abs( draw.getTopX() -

                               draw.getBottomX() ) );

      draw.setHeight( Math.abs( draw.getTopY() -

                                draw.getBottomY() ) );



      draw.setTopX( Math.min( draw.getTopX(), draw.getBottomX() ) );

      draw.setTopY( Math.min( draw.getTopY(), draw.getBottomY() ) );

      draw.status.setText( "Area is " +

                       ( draw.getWidth() * draw.getHeight() ) );

      draw.repaint();

   }



   public void mousePressed( MouseEvent e )

   {

      draw.setTopX( e.getX() );

      draw.setTopY( e.getY() );

   }

}
