Academic Java    Java Tutorial  >  Graphics  >  clip

clip Example

Java clip EXAMPLE output The applet draws a large circle in a black rectangle, then a smaller red circle.

The method clip() is twice used with the graphics context to define where any rendering is to take place, It is the clip shape.

On each occasion after the clip shape is defined, a rectangle is rendered apparently for the whole applet canvas. But the clipping shape defines the particular shape and position to be rendered.
// clip() Example
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;

class ClipExample extends JApplet {

   @Override public void paint(Graphics g) {
      super.paint(g);

      int w=300, h=300; // size of canvas

      Graphics2D g2 = (Graphics2D)g;

      g2.setColor(Color.BLACK);
      g2.fillRect(0, 0, w, h);

      g2.clip(new Ellipse2D.Float(w/4, h/4, w/2, h/2));
      g2.setPaint(new GradientPaint(0, 0, Color.cyan, 0, h/4, Color.blue,true));
      g2.fillRect(0, 0, w, h);

      g2.clip(new Ellipse2D.Float((w/2)-10, (h/2)-10, 20, 20));
      g2.setPaint(Color.red);
      g2.fillRect(0, 0, w, h);

   }
}