Write a Java applet similar to example 4.6 where the applet draws shapes. Your s
ID: 654972 • Letter: W
Question
Write a Java applet similar to example 4.6 where the applet draws shapes. Your shapes to be drawn are a square, circle, rectangle and triangle. Use the necessary class and data types along with import use of JApplet and Graphics as needed to ensure the applet works successfully.
Example 4.6
/* A Shape Drawing Applet
Anderson , Franceschi
*/
import javax.swing.JApplet ;
import java.awt.Graphics ;
public class ShapeDrawingApplet extends JApplet
{
public void paint( Graphics g )
{
super .paint( g ) ;
g.drawRect(100, 50, 40, 100); //rectangle
g.fillRect (200, 70, 80, 80); //solid square
g.fiIIOval (100 , 50, 40, 100); //oval inside the rectangle
g.drawOval (100, 200, 100, 40) ; //same-size oval
// rotated 90 degrees
int centerX = 250, centerY = 225;
int radius = 25;
g.drawOval (centerX - radius, centerY - radius,
radius * 2. radius * 2): // cirlce using radius
// and center
}
}
This is programming in java Thank you for you time.
Explanation / Answer
import javax.swing.JApplet ;
import java.awt.Color;
import java.awt.Graphics ;
public class ShapeDrawingApplet extends JApplet
{
Color redColor; //declare color type objects
Color greenColor;
Color yellowColor;
Color blueColor;
public ShapeDrawingApplet(){
redColor=Color.red; //initialize the color type objects to specific color values
greenColor=Color.green;
yellowColor=Color.yellow;
blueColor=Color.blue;
}
public void paint( Graphics g )
{
super .paint( g ) ; //call paint() method of base class i.e JApplet
g.setColor(redColor); //set the drawing color
g.drawRect(50, 10, 50, 50); //draw square
g.fillRect(50, 10, 50, 50); //fill the square with drawing color
g.setColor(greenColor); //set the drawing color
g.drawOval(50,100,100,100); //draw circle
g.fillOval(50,100,100,100); //fill the circle with drawing color
g.setColor(yellowColor); //set the drawing color
g.drawRect(50, 240, 100, 40); //draw rectangle
g.fillRect(50, 240, 100, 40); //fill the rectangle with drawing color
int[] xPoints={70,120,160}; //define set of x-coordinates for triangle
int[] yPoints={400,300,400}; //define set of y-coordinates for triangle
g.setColor(blueColor); //set the drawing color
g.drawPolygon(xPoints,yPoints,3); //draw triangle
g.fillPolygon(xPoints, yPoints, 3); //fill the triangle with drawing color
}
}
Note: If you are using eclispe to compile and run this code then set the applet size by right clicking on the java source file -> Properties -> Run/Debug Settings -> select applet name and click edit -> goto parameters tab -> set width= 500 and height=500 -> click OK