import java.awt.*; import javax.swing.*; public class ClipTest extends JPanel { public void paint(Graphics g) { // Set the clipping region to a rectangle with rounded corners Shape clipShape = new RoundRectangle2D.Float(50, 50, 200, 200, 50, 50); g.setClip(clipShape); // Draw an image that fills the clipping region Image img = new ImageIcon("example.jpg").getImage(); g.drawImage(img, 0, 0, getWidth(), getHeight(), null); } public static void main(String[] args) { JFrame frame = new JFrame("Clip Test"); frame.getContentPane().add(new ClipTest()); frame.setSize(400, 400); frame.setVisible(true); } }
import java.awt.*; import javax.swing.*; public class ClipTest extends JPanel { public void paint(Graphics g) { // Set the clipping region to a circle g.setClip(100, 100, 100, 100); g.setColor(Color.RED); // Draw a large rectangle that extends beyond the clipping region g.fillRect(0, 0, 200, 200); // Draw an image clipped to within the circle Image img = new ImageIcon("example.jpg").getImage(); g.drawImage(img, 0, 0, getWidth(), getHeight(), null); } public static void main(String[] args) { JFrame frame = new JFrame("Clip Test"); frame.getContentPane().add(new ClipTest()); frame.setSize(400, 400); frame.setVisible(true); } }In this example, the clipping region is set to a circle using the `setClip()` method. A rectangle is drawn that extends beyond the clipping region, but only the portion within the circle is visible. An image is then drawn clipped to within the circle. Package/library: java.awt