ClipBetweenRectangleEllipse2D.java Source code

Java tutorial

Introduction

Here is the source code for ClipBetweenRectangleEllipse2D.java

Source

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ClipBetweenRectangleEllipse2D extends JFrame {
    public ClipBetweenRectangleEllipse2D() {
        getContentPane().add(new DrawingCanvas());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 500);
        setVisible(true);
    }

    public static void main(String arg[]) {
        new ClipBetweenRectangleEllipse2D();
    }
}

class DrawingCanvas extends JPanel {
    DrawingCanvas() {
        setSize(300, 300);
        setBackground(Color.white);
    }

    public void paint(Graphics g) {
        Graphics2D g2D = (Graphics2D) g;

        Graphics2D g2 = (Graphics2D) g;

        int w = getSize().width;
        int h = getSize().height;
        Ellipse2D e = new Ellipse2D.Float(w / 4.0f, h / 4.0f, w / 2.0f, h / 2.0f);
        g2.setClip(e);

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

        Rectangle r = new Rectangle(w / 2, h / 2, w / 2, h / 2);
        g2.clip(r);

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

    }
}