In: Computer Science
Write an applet in Java that creates a yellow colored filled circle on screen. Inside this circle the word “GO” with Arial font and size 24, bold face needs to be printed. Justify your syntax.
I need this answer ASAP PLZ.
A good way to approach this problem is to create a separate method which takes as parameters the x and y co-ordinates and the diameter of the circle. On calling this method, a circle is drawn with center at (x, y) and the passed in diameter. Text is also drawn at (x, y) which is the center of the circle.
Please see the below code and comment for the explanations -
import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
public class AppletExample extends Applet
{
public void createCircleWithText(Graphics g, int x,
int y, int diameter)
{
// draws yellow circle
g.setColor(Color.YELLOW);
int radius = diameter / 2;
g.fillOval(x - radius, y - radius,
diameter, diameter);
// sets the font and color for the
text
String text = "GO";
Font arial = new Font("Arial",
Font.BOLD, 24);
g.setFont(arial);
g.setColor(Color.BLACK);
g.drawString(text, x, y);
// positions the text at the center
of the circle
// FontMetrics fm =
g.getFontMetrics();
// g.drawString(text, x -
fm.stringWidth(text) / 2, y + fm.getAscent() / 2);
}
public void paint(Graphics g)
{
// sets the size of the
window
this.setSize(300, 300);
// gets the center of the
window
int x = getWidth() / 2;
int y = getHeight() / 2;
int diameter = 200;
// creates a circle at the
center
createCircleWithText(g, x, y,
diameter);
}
}
Output
Please note to use the "Run as Applet" option in the IDE.
Note - As the text is drawn from the center of the circle it would not appear exactly in the middle. To have the text exactly in the middle of the circle, we need to subtract the text width from x and add text height (ascent) from y. (Uncomment the below code)
// FontMetrics fm =
g.getFontMetrics();
// g.drawString(text, x -
fm.stringWidth(text) / 2, y + fm.getAscent() / 2);
Screenshot of the code (included for readability)