jeffheaton's picture
in

In addition to drawing rectangles and lines you can also draw more rounded graphical elements. In this section I will show you how to draw ovals. You can also use the same code to draw a circle, since a circle is an oval that has the same height and width.

To draw an oval you will use the drawOval or fillOval method, depending on if you want an oval outline or an oval that has been filled in. The command in Java to draw an oval looks exactly the same as the command to draw rectangle. You can think of the oval drawing commands as drawing an oval that exactly fits inside of the specified rectangle. For example, to draw an oval that fits in the rectangle at (10,10) and is 50 pixels wide and 100 pixels high, you would use the following drawOval method.

g.drawOval(10,10,50,100);

I will now show you a program that displays several random ovals. This applet can be seen in Figure 2.5.

 Drawing Ovals

Figure 2.5: Drawing Ovals

The source code used to make this program is shown in Listing 2.5.

Listing 2.5: Drawing Ovals (OvalApplet.java)

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class OvalApplet extends Applet
{
  public static final int IDEAL_WIDTH = 400;
  public static final int IDEAL_HEIGHT = 400;

  public void paint(Graphics g)
  {
    g.setColor(Color.BLACK);

    g.fillRect(0, 0, getWidth(), getHeight());

    g.setColor(Color.WHITE);
    for (int i = 0; i < 100; i++)
    {
      int x = (int) (Math.random() * getWidth());
      int y = (int) (Math.random() * getHeight());
      int width = (int) (Math.random() * 50) + 5;
      int height = (int) (Math.random() * 50) + 5;
      int color = (int) (Math.random() * 5) + 1;
      switch (color)
      {
      case 1:
        g.setColor(Color.BLUE);
        break;
      case 2:
        g.setColor(Color.CYAN);
        break;
      case 3:
        g.setColor(Color.YELLOW);
        break;
      case 4:
        g.setColor(Color.GREEN);
        break;
      case 5:
        g.setColor(Color.RED);
        break;
      }
      g.fillOval(x, y, width, height);
    }
  }

  public static void main(String args[])
  {
    Applet applet = new OvalApplet();
    Frame frame = new Frame();
    frame.addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        System.exit(0);
      }
    });

    frame.add(applet);
    frame.setSize(IDEAL_WIDTH, IDEAL_HEIGHT);
    frame.show();
  }
}

This program loops through and draws random ovals in random colors. The random colors are displayed by generating a random number between 1 and 5. This random color number is then mapped to 5 preset colors.


Copyright 2005 - 2012 by Heaton Research, Inc.. Heaton Research™ and Encog™ are trademarks of Heaton Research. Click here for copyright, license and trademark information.