import java.awt.*; public class DrawRectangleExample extends Component { public void paint(Graphics g) { // Draws a rectangle with top left corner at (30, 30) // and with dimensions 50x80 pixels g.drawRect(30, 30, 50, 80); } }
import java.awt.*; import java.util.Random; public class DrawRandomRectangleExample extends Component { public void paint(Graphics g) { Random random = new Random(); // Randomly generates x, y, width, height, and color values int x = random.nextInt(500); int y = random.nextInt(500); int width = random.nextInt(200); int height = random.nextInt(200); int red = random.nextInt(256); int green = random.nextInt(256); int blue = random.nextInt(256); Color randomColor = new Color(red, green, blue); // Draws a rectangle with random dimensions and color g.setColor(randomColor); g.drawRect(x, y, width, height); } }These examples use the java.awt.Graphics package library, which is a part of the Java Abstract Window Toolkit (AWT). It provides a way to create and manage graphical user interfaces, as well as handle input events such as mouse clicks and keyboard presses.