import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Example06 extends Applet
   implements MouseListener, MouseMotionListener {

   int window_x, window_y;    // upper-left corner of the window
   int window_width = 60, window_height = 40; // dimensions of window
   static final int window_resize_box_size = 15;
   boolean isWindowBeingDragged = false;
   boolean isWindowBeingResized = false;

   int mouse_x, mouse_y;

   public void init() {
      setBackground( Color.black );

      window_x = getWidth()/2 - window_width/2;
      window_y = getHeight()/2 - window_height/2;

      addMouseListener( this );
      addMouseMotionListener( this );
   }

   boolean isInsideWindow( int x, int y ) {
      return
         window_x <= x && x < window_x+window_width
         && window_y <= y && y < window_y+window_height;
   }
   boolean isInsideWindowResizeBox( int x, int y ) {
      return
         window_x+window_width-window_resize_box_size <= x
         && x < window_x+window_width
         && window_y+window_height-window_resize_box_size <= y
         && y < window_y+window_height;
   }

   public void mouseEntered( MouseEvent e ) { }
   public void mouseExited( MouseEvent e ) { }
   public void mouseClicked( MouseEvent e ) { }
   public void mousePressed( MouseEvent e ) {
      mouse_x = e.getX();
      mouse_y = e.getY();
      if ( isInsideWindow( mouse_x, mouse_y ) ) {
         if ( isInsideWindowResizeBox( mouse_x, mouse_y ) ) {
            isWindowBeingResized = true;
         }
         else isWindowBeingDragged = true;
      }
      e.consume();
   }
   public void mouseReleased( MouseEvent e ) {
      isWindowBeingDragged = isWindowBeingResized = false;
      e.consume();
   }
   public void mouseMoved( MouseEvent e ) { }
   public void mouseDragged( MouseEvent e ) {
      int new_mouse_x = e.getX();
      int new_mouse_y = e.getY();
      int delta_x = new_mouse_x - mouse_x;
      int delta_y = new_mouse_y - mouse_y;
      if ( isWindowBeingDragged ) {
         window_x += delta_x;
         window_y += delta_y;
         repaint();
         e.consume();
      }
      else if ( isWindowBeingResized ) {
         window_width += delta_x;
         window_height += delta_y;
         if ( window_width < 2*window_resize_box_size )
            window_width = 2*window_resize_box_size;
         if ( window_height < 2*window_resize_box_size )
            window_height = 2*window_resize_box_size;
         repaint();
         e.consume();
      }
      mouse_x = new_mouse_x;
      mouse_y = new_mouse_y;
   }

   public void paint( Graphics g ) {
      g.setColor( Color.white );
      g.drawRect( window_x, window_y, window_width-1, window_height-1 );
      g.drawRect(
         window_x + window_width - window_resize_box_size,
         window_y + window_height - window_resize_box_size,
         window_resize_box_size-1,
         window_resize_box_size-1
      );
   }
}

