handout #8

CSE142—Computer Programming I

Sample Graphics Program

Program File Drawing.java

// Stuart Reges

// 10/10/04

//

// This program draws a picture that includes a figure composed of squares

// and circles at the top and a series of blue diamonds at the bottom.

 

import java.awt.*;

 

public class Drawing {

    public static void main(String[] args) {

        DrawingPanel p = new DrawingPanel(400, 600);

        p.setBackground(Color.CYAN);

        Graphics g = p.getGraphics();

        drawFigure1(g);

        drawDiamonds(g);

    }

 

    // Draws a figure composed of squares, circles and a line

    public static void drawFigure1(Graphics g) {

        g.setColor(Color.RED);

        for (int i = 1; i <= 5; i++)

            g.drawRect(50, 50, i * 20, i * 20);

        g.drawRect(150, 150, 100, 100);

        for (int i = 1; i <= 5; i++)

            g.drawOval(250 - 20 * i, 250 - 20 * i, 20 * i, 20 * i);

        g.setColor(Color.BLACK);

        g.drawLine(50, 50, 250, 250);

    }

 

    // Draws a series of blue diamonds at the bottom of the screen

    public static void drawDiamonds(Graphics g) {

        g.setColor(Color.BLUE);

        for (int i = 0; i < 5; i++)

            drawDiamond(g, 45 * i, 300 + 45 * i, 90, 60);

    }

 

 

    // Draws a diamond shape whose bounding rectangle has upper left corner

    // (x, y) with the given width and height.

    public static void drawDiamond(Graphics g, int x, int y,

                                   int width, int height) {

        int midX = x + width/2;

        int midY = y + height/2;

        g.drawLine(x, midY, midX, y);

        g.drawLine(x, midY, midX, y + height);

        g.drawLine(midX, y, x + width, midY);

        g.drawLine(midX, y + height, x + width, midY);

    }

}

Graphical output