import javax.swing.*; import java.awt.*; import java.awt.geom.*; import java.awt.event.*; public class ClipTest extends JPanel { Rectangle2D r; Ellipse2D e; public static void main(String[] args) { JFrame f = new JFrame("ClipTest"); f.setContentPane(new ClipTest()); f.setSize(500, 300); f.setVisible(true); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; //Create a ellipse in the center of this //JPanel and a rectangle in the upper left corner. //Next two line can not be placed in the constructor since the the panel //report 0x0 sixe there. e = new Ellipse2D.Float(getWidth()/4f, getHeight()/4f, getWidth()/2f, getHeight()/2f); r = new Rectangle2D.Float(0, 0, getWidth()/2, getHeight()/2); //Set the clipping area to the ellipse. g2.setClip(e); g2.setColor(Color.cyan); //The next line seems to paint the whole JPanel, but only //the ellipse gets painted sinve we have restricted the clipping area. g2.fillRect(0, 0, getWidth(), getHeight()); //Set the clipping area to the intersection //of the ellipse and the rectangle. g2.clip(r); g2.setColor(Color.magenta); //Paint the new clipping area in another color. g2.fillRect(0, 0, getWidth(), getHeight()); } }