teaching machines

CS 145 Lab 4 – Methods

September 30, 2016 by . Filed under cs145, fall 2016, labs.

Welcome to lab 4!

If you have checkpoints from the last to show your instructor or TA, do so immediately. No credit will be given if you have not already completed the work, nor will credit be given after the first 10 minutes of this lab.

You must work with a partner that you have not worked with before.

Checkpoint 1

Person A types.

You’ve seen Practice-It!, which accompanies the textbook and is great for trying out the ideas you read about. There’s also Coding Bat. Go there now and make an account.

Complete the follow exercises:

If you feel like you could use extra practice with the concepts we discuss in this class, keep working away at the problems on Coding Bat and Practice-It! Don’t wait for them to be assigned.

Checkpoint 2

Person B types. Open your Eclipse workspace and create a package named lab04. Select the newly made package and paste in the class Canvas:

package lab04;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Canvas {
  private JFrame frame;
  private BufferedImage image;
  public Canvas(int width, int height) {
    image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    frame = new JFrame("Canvas");
    frame.add(new CanvasPanel());
    frame.setSize(width, height);
  public Graphics2D getGraphics() {
    return image.createGraphics();
  public void show() {
  private class CanvasPanel extends JPanel {
    public void paintComponent(Graphics g) {
      g.drawImage(image, 0, 0, null);

This class alleviates some of the burden of popping open a window and programmatically drawing. You don’t need to modify it in any way; your other code will construct an instance of it.

Create a class named Snow and add these lines to its main method:

Canvas canvas = new Canvas(512, 512); // feel free to adjust the height and width
Graphics2D graphics = canvas.getGraphics();

// call drawing methods here


Complete the following tasks: