Q.
Write an applet to draw different graphical shapes
Here's a simple Java applet that draws different graphical shapes (line, rectangle, oval, and
string). This code demonstrates how to use the Graphics class in an applet to draw basic
shapes.
Java Applet Example to Draw Different Graphical Shapes:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/* <applet code="GraphicalShapesApplet" width="400" height="400">
</applet>*/
public class GraphicalShapesApplet extends Applet {
// The paint method is called automatically to render shapes on the applet window
public void paint(Graphics g) {
// Drawing a line
g.setColor(Color.RED); // Set line color to red
g.drawLine(50, 50, 150, 50); // Line from (50,50) to (150,50)
// Drawing a rectangle
g.setColor(Color.GREEN); // Set rectangle color to green
g.drawRect(50, 100, 200, 100); // Rectangle at (50, 100) with width 200 and height 100
// Drawing a filled rectangle
g.setColor(Color.YELLOW); // Set filled rectangle color to yellow
g.fillRect(50, 250, 200, 100); // Filled rectangle at (50, 250)
// Drawing an oval
g.setColor(Color.BLUE); // Set oval color to blue
g.drawOval(300, 100, 150, 100); // Oval inside a rectangle at (300, 100)
// Drawing a filled oval
g.setColor(Color.ORANGE); // Set filled oval color to orange
g.fillOval(300, 250, 150, 100); // Filled oval inside a rectangle at (300, 250)
// Drawing a string
g.setColor(Color.BLACK); // Set text color to black
g.drawString("Hello, Java Applet!", 50, 400); // Draw text at (50, 400)
}}
Explanation:
1. Applet Class: The applet extends the Applet class, and the paint method is overridden to
perform drawing operations.
2. Graphics Object: The Graphics object (g) is passed to the paint method, which allows
drawing on the applet.
3. Drawing Shapes:
Line: g.drawLine(50, 50, 150, 50) draws a red line from coordinates (50, 50) to (150, 50).
Rectangle: g.drawRect(50, 100, 200, 100) draws a green rectangle at (50, 100) with width 200
and height 100.
Filled Rectangle: g.fillRect(50, 250, 200, 100) draws and fills a yellow rectangle at (50, 250).
Oval: g.drawOval(300, 100, 150, 100) draws a blue oval at (300, 100) with width 150 and height
100.
Filled Oval: g.fillOval(300, 250, 150, 100) draws and fills an orange oval at (300, 250).
String: g.drawString("Hello, Java Applet!", 50, 400) draws a text message at (50,
This simple applet draws a red line, a green rectangle, a yellow filled rectangle, a blue oval, an
orange filled oval, and a text string. You can modify the colors and positions to explore