Draw shapes

This code sample demonstrates how to draw various shapes and change colors.1

The uits for the parameters are pixels and they work as follows:

  • drawRect
    • First two terms are the x and y coordinate of the top left corner. Followed by widht and height of rectangle
  • drawLine
    • X and Y coordinates of the star of the line followed by the coordinates of the end
  • drawOval
    • Imagine a box around the oval. The parameters are the x and y coordinates of the top left of the rectangle followed by the widht and height
  • drawArc
    • An arc is part of an oval, so the first 4 parameters define the oval it is taken from as for the drawOval method. Then the start angle is given measured anticlockwise from east and the final parameter is the arc angle.
  • setColour
    • The available colours are black, gray, orange, yellow, blue, green, pink, cyan, lightGray, red, darkGray, magenta, white.

The parameters for the fill methods are the same as for the draw methods. If these descriptions are a little confusing compare the code with the result to clarify them.

import java.awt.*;
import java.applet.Applet;

public class FirstShapes extends Applet

public void paint (Graphics g)

g.drawRect (20, 30, 80, 40);
g.drawOval (120, 30, 50, 50);
g.setColor (Color.black);
g.fillRect (30, 100, 80, 40);
g.fillOval (120, 100, 50, 50);
g.drawLine (30, 160, 130, 170);
g.drawArc (30, 180, 50, 50, 60, 40);
g.setColor (Color.red);
g.fillArc (120, 180, 50, 50, 60, 40);



This is the result:

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License