Graphics g = getGraphics(); g.setColor(Color.RED); g.clipRect(50, 50, 100, 100); // limit to a rectangle from (50,50) to (150,150) g.drawRect(75,75,50,50); // draw within the limited area
Graphics g = getGraphics(); g.setColor(Color.BLUE); g.clipRect(100, 100, 50, 50); // limit to a rectangle from (100,100) to (150,150) g.fillOval(75, 75, 100, 100); // draw an oval that extends beyond the limited areaThis code will fill a blue ellipse within the specified limited area, even though the oval extends beyond the boundaries of the limited area. Both of these examples use the Graphics object, which can be obtained in various ways depending on the context (for example, by calling the paint method of a component or creating a BufferedImage). The clipRect method is called on the Graphics object to specify a limited area for rendering, and any subsequent drawing calls will be constrained to that area until the clip is changed or reset to the full extent of the rendering surface.