| When the image moves, only a fraction of the total 
              display in the red rectangle area below, is changed. No point in 
              redrawing the whole image. 
 Clipping is the technique to do limit the redrawing 
              to just a chosen part of the image.  The graphics context can be told by the clipRect() 
              method to only accept changes in the clipped area. The only hard part is calculating the red outlined 
              area above, regardless of which way the mouse moves. Study the clip() 
              method below to see how this is done.  
              
                 
                  | Clipping_Applet7.java 
                      Resources: Apollo16Lander.jpg
 |   
                  | import 
                      java.awt.*; import java.awt.event.*;
 // 
                      Extend the Update_Applet7 class public 
                      class Clipping_Applet7 extends Update_Applet7 {
 int newX, newY;
 int imageWd, imageHt;
 
 public void mouseDragged( MouseEvent e )
 {
 newX=e.getX();
 newY=e.getY();
 repaint();
 }
   // 
                      Here we do the math to get the clip region// 
                    Override update. Keep track here ofvoid clipToAffectedArea( Graphics g,
 int oldX, int oldY, int nextX, 
                      int nextY,
 int width, int height) {
 int x = Math.min( oldX, nextX );
 int y = Math.min( oldy, nextY );
 int w = ( Math.max( oldY, nextX )
 + width ) - x;
 int h = ( Math.max( oldY, nextY )
 + height ) - y;
 g.clipRect( x, y, w, h );
 }
 // position of the image.
 public void update( Graphics g )
 {
 int lastX = currentX, lastY = currentY;
 currentX = newX;
 currentY = newY;
 clipToAffectedArea( g,
 lastX, lastY,currentX,
 currentY, 
                    imageWd, imageHt );
 paint( g );
 }
 }
 |    References & Web Resources Latest update: March 8, 2006 |