Way2Java

Java Clear Copy Graphics Area

java.awt.Graphics class comes with many methods of drawing and also with some non-drawing methods that will support drawing indirectly. These methods include clearRect() and copyArea() etc.

clearRect() clears a part of graphical area where a drawing may exist with its own background. When cleared, the cleared area shows the background area of the frame (a proof that some part of the figure area is cleared).

copyArea() copies of a part of drawing area to another space on the frame. This helps to duplicate a figure or take some part of the figure.

Description of supporting methods

  1. void clearRect(int x, int y, int width, int height): Clears a rectangular area as per the parameter list.
  2. void copyArea(int x, int y, int width, int height, int dx, int dy): Copies a part of the graphics area to the relative area given by dx and dy.

Parameter Particulars

Following program illustrates both the methods.

import java.awt.*;
public class CAndC extends Frame
{
  public CAndC()
  {
    setTitle("Part Clearing and Part Copying");
    setSize(600, 250);
    setVisible(true);
  }
  public void paint(Graphics g)              
  {                                                           
    g.fillRect(40, 80, 150, 100);// rectangle filled with black color
                  //clears some portion (looks white, the frame color)
    g.clearRect(60, 100, 100, 70); 

    g.setColor(Color.magenta);
    g.fillRect(240, 80, 150, 100);// rectangle filled with magenta
    g.copyArea(270, 100, 70, 100, 160, 20); // copies some portion
  }
  public static void main(String args[])
  {
    new CAndC();
  }
}

                    g.fillRect(40, 80, 150, 100);         
          	    g.clearRect(60, 100, 100, 70); 
                    

clearRect() clears a rectangle area of 60, 100 x and y coordinates of width 100 and height 70 pixels within the graphics area drawn earlier by fillRect() method in default black color. The cleared area is seen with white color, the background color of the frame.

                    g.setColor(Color.magenta);
	            g.fillRect(240, 80, 150, 100);   
          	    g.copyArea(270, 100, 70, 100, 160, 20);    
                  

copyArea() method copies the graphics area of width 70 and height 100 starting from x and y coordinates 270 and 100. This area is copied to another area represented by x coordinate 430 (270+160) and y coordinate 120 (100+20).