import java.awt.*; public class ClearRectExample1 extends Frame { public ClearRectExample1() { super("Clear Rect Example 1"); setSize(400, 400); setVisible(true); } public void paint(Graphics g) { // Set the color to blue g.setColor(Color.BLUE); // Draw a rectangle at (50, 50) with width of 100 and height of 100 g.drawRect(50, 50, 100, 100); // Clear a rectangle at (75, 75) with width of 50 and height of 50 g.clearRect(75, 75, 50, 50); } public static void main(String[] args) { new ClearRectExample1(); } }
import java.awt.*; import javax.swing.*; public class ClearRectExample2 extends JPanel { public ClearRectExample2() { setPreferredSize(new Dimension(400, 400)); } public void paintComponent(Graphics g) { // Set the color to red g.setColor(Color.RED); // Draw a rectangle at (50, 50) with width of 100 and height of 100 g.drawRect(50, 50, 100, 100); // Clear a rectangle at (75, 75) with width of 50 and height of 50 g.clearRect(75, 75, 50, 50); } public static void main(String[] args) { JFrame frame = new JFrame("Clear Rect Example 2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new ClearRectExample2()); frame.pack(); frame.setVisible(true); } }This example uses a JPanel to draw the rectangle on the screen. The clearRect method is still used to clear a smaller rectangle within the main rectangle. Both of these examples use the java.awt package to draw graphics on the screen.