In: Computer Science
Programming Assignment #3: SimpleFigure and Circles
Program Description:
This assignment will give you practice with value parameters, using Java objects, and graphics. This assignment has 2 parts; therefore you should turn in two Java files.
You will be using a special class called DrawingPanel written by the instructor, and classes called Graphics and Color that are part of the Java class libraries.
Part 1 of 2 (4 points)
Simple Figure, or your own drawing
For the first part of this assignment, turn in a file named SimpleFigure.java that draws a figure on the screen using the DrawingPanel provided in class. You may draw any figure you like that meets the following criteria:
The DrawingPanel's size must be at least 100 x 100 pixels.
You must draw at least one line, one rectangle, and one oval that
are visible on the screen.
You must use at least three different visible colors in your
figure.
The loose guidelines for Part 1 mean that if you like, you can be creative and draw any figure you like! After the assignment is turned in, the instructor may anonymously show off some of the neat figures drawn by students for everyone to see.
[hw3_expected_output_part1] If you do not want to create your own figure, the following is a default figure you may draw for Part 1. If your code draws this figure correctly, you will receive full credit for Part 1. This figure contains the following properties and shapes:
A DrawingPanel of size 250 x 200 with a yellow background.
A green rectangle with top-left corner at (10, 20) and size 200 x
160 pixels.
Red ovals with top-left corners at (10, 20) and (110, 100) of size
100 x 80 pixels.
Black lines from (10, 60) to (110, 60), from (60, 20) to (60, 100),
from (110, 140) to (210, 140), and from (160, 100) to (160,
180).
import java.awt.*;
// so I can use Graphics
public class OutlineExample { public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(150, 70);
Graphics g = panel.getGraphics(); // inner red fill
g.setColor(Color.RED);
g.fillRect(20, 10, 100, 50); // black outline
g.setColor(Color.BLACK);
g.drawRect(20, 10, 100, 50);
}
}
Since a major new concept for this assignment is parameter-passing, you may optionally wish to try using parameterized methods to draw your figure. For example, the default picture above has a repeated figure of an oval with black lines through it. This figure could be turned into a parameterized static method with parameters for the figure's position.
However, parameterized methods are not required for Part 1, and you will not be penalized if you do not use them. Your entire score for Part 1 will be based on its external correctness as defined above.
Part 2 of 2 (16 points)
Circles
[hw3_expected_output_part2] Part 2 of this assignment asks you to draw a complex figure using parameterized methods. You must reproduce exactly the figure shown in the picture on this page; you may not create your own figure for this part. Name your Java class Circles and your file Circles.java.
You will use complex computations to draw a figure that has several levels of structure. You are to produce the figure image as output. Your program should exactly reproduce the following image. (The image in this document was taken when running the program on Windows; if you use another platform, the decorations around the window may look slightly different, but the actual contents of the window should be identical.)
This image has several levels of structure. You will find that there is a basic subfigure that occurs throughout, which is a green square with concentric circles inside it. The subfigure is repeated to form larger figures.
A major part of this assignment is showing that you understand parameters. Therefore, you should write parameterized methods to represent the tasks of drawing one subfigure and of drawing a larger figure composed of many subfigures.
Figure Specifications:
The overall panel has a cyan background and is 400 pixels wide and 425 pixels high. Each of the subfigures is has an overall rectangular green background, containing a yellow inner circular background, which has black circles, squares, and X lines drawn on it.
The four figures on your drawing panel should have the following properties.
Description
(x, y) position
number of rows and columns
size of each subfigure, in pixels
number of concentric circles in each subfigure
top-left figure
(0, 0)
1 x 1
100 x 100
10
bottom-left figure
(18, 175)
6 x 6
24 x 24
4
top-right figure
(180, 25)
5 x 5
40 x 40
5
bottom-right figure
(180, 250)
4 x 4
36 x 36
6
Implementation Guidelines for Part 2:
You are required to have two particular static methods that are described below. You will not be using class constants for this assignment. Instead, you will be exploring the use of value parameters.
This program does not require a lot of lines of code, but the numeric computations and parameter-passing required are not simple. You might very well find yourself overwhelmed with the amount of detail you have to handle all at once. A famous computer scientist named Brian Kernighan once said, “Controlling complexity is the essence of computer programming,” which is why this makes a good exercise for a beginning computer scientist. You will find that the techniques of decomposition and iterative enhancement described in chapter 1 will help you in this situation.
Because it is difficult to correctly implement such a complex program all at once, instead start with one smaller piece of the problem. In particular, you should write a static method that draws one square with concentric circles inside of it. That subfigure is repeated throughout this image, so it makes sense to have a separate method for producing it. Start with the subfigure in the upper-left part of the screen. It is not in a grid pattern; it is just the subfigure itself (one set of concentric circles in a square).
Your first version of this method could draw the specific subfigure in the upper-left corner (always drawing it in that position, always making it 100 pixels wide, always having 10 concentric circles), but you will want to generalize this with the use of parameters. You should be able to call it with different sizes, different locations and different numbers of concentric circles.
The drawing commands we are using are defined in terms of integers, which leaves open the possibility that things won’t divide up evenly. You don’t have to worry about this possibility. In particular, you may assume that the subfigure height will always be a multiple of the number of concentric circles you are supposed to draw (e.g., 10 circles in a figure 100 wide, 6 circles in a figure 36 wide, 5 circles in a figure 40 wide, 4 circles in a figure 24 wide).
Once you have completed the static method that produces one of these subfigures, write another static method that produces a square grid of these subfigures. You will call this method several different times from main to produce the grids of the overall figure. It will have a lot of parameters to be flexible enough to draw each of these grids. The key point is that a single method can be used that produces all three grids.
You could compare your result with the provided output image: Assignment2_output.png (https://alamo.instructure.com/courses/1043448/files/folder/Assignments?preview=102316391).
The Graphics and Color classes are part of Java, but you will need to include the following line of code at the beginning of your program file to be able to use them:
import java.awt.*;
Stylistic Guidelines:
For this assignment you are limited to the language features in Chapters 1 through 3; you are not allowed to use more advanced features to solve the problem. You cannot, for example, make use of if/else statements to solve this task. You will, however, use the DrawingPanel and Graphics classes described at the end of Chapter 3 as well as the color constants from the Color class, as described in Chapter 3.
Continue to use static methods to structure your solution as described previously; this time, write static methods that use parameters. In grading, we will require two static methods: one that draws a subfigure with just one square and its concentric circles, and one for producing a grid of such subfigures that is called many different times to produce the various figures on the screen.
Give meaningful names to methods and variables in your code. Follow Java's naming standards about the format of ClassNames, methodAndVariableNames, and CONSTANT_NAMES. Localize variables whenever possible -- that is, declare them in the smallest scope in which they are needed.
Include a comment at the beginning of your program with basic information and a description of the program and include a comment at the start of each method.
Submission and Grading:
Name your Part 1 file SimpleFigure.java and your Part 2 file Circles.java. You do not have to turn in DrawingPanel.java. This assignment is worth 20 points total.
Part of your program's score will come from its "external correctness." External correctness for Part 1 measures whether you have met the constraints on the figure as specified on the first page, including having sufficient number of shapes and colors. External correctness for Part 2 measures whether the figure you draw matches exactly what is expected.
The rest of your program's score will come from its "internal correctness." Internal correctness will only be measured for Part 2; you will not be penalized for stylistic issues on Part 1. Internal correctness measures whether your source code follows the stylistic guidelines specified in this document. This includes using for loops to capture repetition in the figures, capturing the structure of the figure using the two parameterized static methods specified, commenting, naming identifiers, and indentation of your source code.
Few things were missing in your question was:
But I figured out the all the things and now pasting everything below with output.
To understand any part of code, read the comments in the code
PART 1:
SimpleFigure.java
import java.awt.Color;
import java.awt.Graphics;
public class SimpleFigure {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(250, 200);
Graphics g = panel.getGraphics();
// A green rectangle with top-left corner at (10, 20) and size 200 x 160 pixels.
g.setColor(Color.GREEN);
g.fillRect(10, 20, 200, 160);
// Red ovals with top-left corners at (10, 20) and (110, 100) of size 100 x 80 pixels.
g.setColor(Color.RED);
g.fillOval(10, 20, 100, 80);
//Black lines
// from (10, 60) to (110, 60),
// from (60, 20) to (60, 100),
// from (110, 140) to (210, 140), and
// from (160, 100) to (160, 180).
g.setColor(Color.BLACK);
g.drawLine(10, 60, 110, 60);
g.drawLine(60, 20, 60, 100);
g.drawLine(110, 140, 210, 140);
g.drawLine(160, 100, 160, 180);
}
}
output:
PART 2:
Circles.java
import java.awt.Color;
import java.awt.Graphics;
public class Circles {
/*
* Creating 10 concentric circles
* reducing radius/diameter of each circle by (r*i)/cnt)
* adding (r*i)/cnt)/2 to x,y
*
* */
public static void cCircles(DrawingPanel panel, int x, int y, int r, int cnt) {
Graphics g = panel.getGraphics();
g.setColor(Color.YELLOW);
g.fillOval(x, y, r, r);
g.setColor(Color.BLACK);
for(int i=0;i
int r1 = r-((r*i)/cnt);
int xy = ((r*i)/cnt)/2;
g.drawOval(x+ xy, y+ xy, r1, r1);
} } /* * Drawing lines inside
rectangle * * * */ public static void
rLines(DrawingPanel panel,int x,int y,int p) {
Graphics g = panel.getGraphics();
g.setColor(Color.BLACK);
g.drawLine(x, y, x, y+p);
g.drawLine(x, y, p+x, y);
g.drawLine(x+p, y, x+p, y+p);
g.drawLine(x, y+p, p+x, p+y);
g.drawLine(x, y, x+p, y+p);
g.drawLine(x+p, y, x, p+y);
g.drawLine(x+(p/2), y, x+(p/2), p+y);
g.drawLine(x, y+(p/2), x+p, y+(p/2)); } /* * Drawing main
rectangle * Calling all functions
here to make base figure * * */ public static void
mainRectangle(DrawingPanel panel,int x,int y,int p,int cnt){
Graphics g = panel.getGraphics();
g.setColor(Color.GREEN);
g.fillRect(x, y, p, p);
cCircles(panel,x,y,p,cnt);
rLines(panel,x,y,p); } /* * Calling mainRectangle
function together here to make matrix of rectangles * */ public static void
complexFigureFinal(DrawingPanel panel,int x,int y,int p,int cnt,int
r,int c){
for(int i=0;i
for(int j=0;j
mainRectangle(panel,x+(p*j),y+(p*i),p,cnt);
}
} } public static void
main(String[] args) {
DrawingPanel panel = new DrawingPanel(400, 475);
panel.setBackground(Color.CYAN);
//Creating 4 complex figure given
complexFigureFinal(panel,0,0,100,10,1,1);
complexFigureFinal(panel,18,175,24,4,6,6);
complexFigureFinal(panel,180,25,40,5,5,5);
complexFigureFinal(panel,180,250,36,4,6,6); } } Output:
Required file: DrawingPanel.java /* Stuart Reges and Marty Stepp 07/01/2005 The DrawingPanel class provides a simple interface for drawing
persistent images using a Graphics object. An internal BufferedImage object
is used to keep track of what has been drawn. A client of the class
simply constructs a DrawingPanel of a particular size and then draws on
it with the Graphics object, setting the background color if they so
choose. To ensure that the image is always displayed, a timer calls
repaint at regular intervals. */ import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import javax.swing.event.*; public class DrawingPanel implements ActionListener { public static final int DELAY = 250; // delay
between repaints in millis private static final String
DUMP_IMAGE_PROPERTY_NAME = "drawingpanel.save"; private static String TARGET_IMAGE_FILE_NAME
= null; private static final boolean PRETTY = true;
// true to anti-alias private static boolean DUMP_IMAGE = true; //
true to write DrawingPanel to file private int width, height;
// dimensions of window frame private JFrame
frame; // overall
window frame private JPanel
panel; // overall
drawing surface private BufferedImage image; // remembers
drawing commands private Graphics2D
g2; // graphics context
for painting private JLabel
statusBar; // status bar showing mouse
position private long createTime; static {
TARGET_IMAGE_FILE_NAME =
System.getProperty(DUMP_IMAGE_PROPERTY_NAME); DUMP_IMAGE =
(TARGET_IMAGE_FILE_NAME != null); } // construct a drawing panel of given width
and height enclosed in a window public DrawingPanel(int width, int height)
{ this.width =
width; this.height =
height; this.image = new
BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); this.statusBar = new
JLabel(" ");
this.statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK)); this.panel = new
JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
this.panel.setBackground(Color.WHITE);
this.panel.setPreferredSize(new Dimension(width, height)); this.panel.add(new
JLabel(new ImageIcon(image))); // listen to mouse
movement MouseInputAdapter
listener = new MouseInputAdapter() {
public void mouseMoved(MouseEvent e) {
DrawingPanel.this.statusBar.setText("(" + e.getX() + ", " +
e.getY() + ")");
}
public void mouseExited(MouseEvent e) {
DrawingPanel.this.statusBar.setText(" ");
} };
this.panel.addMouseListener(listener);
this.panel.addMouseMotionListener(listener); this.g2 =
(Graphics2D)image.getGraphics();
this.g2.setColor(Color.BLACK); if (PRETTY) {
this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
this.g2.setStroke(new BasicStroke(1.1f)); } this.frame = new
JFrame("CS307 Drawing Panel");
this.frame.setResizable(false);
this.frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (DUMP_IMAGE) {
DrawingPanel.this.save(TARGET_IMAGE_FILE_NAME);
}
System.exit(0);
} });
this.frame.getContentPane().add(panel);
this.frame.getContentPane().add(statusBar, "South");
this.frame.pack();
this.frame.setVisible(true); if (DUMP_IMAGE) {
createTime = System.currentTimeMillis();
this.frame.toBack(); } else {
this.toFront(); } // repaint timer so
that the screen will update new Timer(DELAY,
this).start(); } // used for an internal timer that keeps
repainting public void actionPerformed(ActionEvent e)
{
this.panel.repaint(); if (DUMP_IMAGE
&& System.currentTimeMillis() > createTime + 4 * DELAY)
{
this.frame.setVisible(false);
this.frame.dispose();
this.save(TARGET_IMAGE_FILE_NAME);
System.exit(0); } } // obtain the Graphics object to draw on the
panel public Graphics2D getGraphics() { return this.g2; } // set the background color of the drawing
panel public void setBackground(Color c) {
this.panel.setBackground(c); } // show or hide the drawing panel on the
screen public void setVisible(boolean visible) {
this.frame.setVisible(visible); } // makes the program pause for the given
amount of time, // allowing for animation public void sleep(int millis) { try {
Thread.sleep(millis); } catch
(InterruptedException e) {} } // take the current contents of the panel and
write them to a file public void save(String filename) { String extension =
filename.substring(filename.lastIndexOf(".") + 1); // create second
image so we get the background color BufferedImage image2
= new BufferedImage(this.width, this.height,
BufferedImage.TYPE_INT_RGB); Graphics g =
image2.getGraphics();
g.setColor(panel.getBackground()); g.fillRect(0, 0,
this.width, this.height);
g.drawImage(this.image, 0, 0,
panel); // write file try {
ImageIO.write(image2, extension, new java.io.File(filename)); } catch
(java.io.IOException e) {
System.err.println("Unable to save image:\n" + e); } } // makes drawing panel become the frontmost
window on the screen public void toFront() {
this.frame.toFront(); } }