Monday, January 16, 2012

Brick Wall java Programming

Question

PP 6.15 Design and implement a program that draws a brick wall pattern in which each row of bricks is offset from the row above and below it.

Solution

//*************************************
// Brick_Wall_Panel.java
// CS151A, Assignment 6
// Panel for Brick Wall
//*************************************

import javax.swing.*;
import java.awt.*;

public class Brick_Wall_Panel extends JPanel
{
    //Sets up Panel//
    public Brick_Wall_Panel()
    {
        setBackground (Color.darkGray);
        setPreferredSize (new Dimension (500,500));
    }

    //Paints Bricks//
    public void paintComponent (Graphics page)
    {
        super.paintComponent (page);
        int x = 0;
        int y = 0;
        int width = 25;
        int height = 15;
        int panel_width = getWidth();
        int panel_height = getHeight();
        int space = 2;
        int stagger = -10;

        for(int count = 0; (count <= panel_width); count++)
        {
            for (int count2 = 0; count2 <= panel_width; count2++)
            {
                if ((count % 2 == 0) && !(count2 % 2 == 0))
                {
                page.setColor (Color.red);
                page.fillRect(x + stagger,y,width,height);
                x = x + width + space;
                }
                else if ((count2 % 2 == 0) && !(count % 2 == 0))
                {
                page.setColor (Color.red);
                page.fillRect(x,y,width,height);
                x = x + width + space;
                }
            }
            y = y + height + space;
            x = 0;
        }
    }
}

//******************************
// Brick_Wall_Driver.java
// CS151A, Assignment 6
// Contains Main Method
//******************************

import javax.swing.*;
import java.awt.*;

public class Brick_Wall_Driver
{
    public static void main (String[] args)
    {
        JFrame frame = new JFrame ("Brick_Wall_Driver");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Brick_Wall_Panel panel = new Brick_Wall_Panel();

        frame.getContentPane().add(new Brick_Wall_Panel());
        frame.pack();
        frame.setVisible(true);
    }
}

No comments:

Post a Comment