Clipping.java Source code

Java tutorial

Introduction

Here is the source code for Clipping.java

Source

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Clipping extends JPanel implements ActionListener {
    int x = 8, y = 8, radius = 90;
    Timer timer;
    Image image = new ImageIcon("yourImage.png").getImage();
    double delta[] = { 3, 3 };

    public Clipping() {
        timer = new Timer(15, this);
        timer.start();
    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setClip(new Ellipse2D.Double(x, y, radius, radius));
        g2d.drawImage(image, 5, 5, null);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new Clipping());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        int w = 400;
        int h = 400;

        if (x < 0) {
            delta[0] = Math.random() % 4 + 5;
        } else if (x > w - radius) {
            delta[0] = -(Math.random() % 4 + 5);
        }

        if (y < 0) {
            delta[1] = Math.random() % 4 + 5;
        } else if (y > h - radius) {
            delta[1] = -(Math.random() % 4 + 5);
        }

        x += delta[0];
        y += delta[1];

        repaint();
    }
}