teaching machines

CS 145 Lab 4 – Methods

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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(width, height);
  }
  
  public Graphics2D getGraphics() {
    return image.createGraphics();
  }
  
  public void show() {
    frame.setVisible(true);
  }
  
  private class CanvasPanel extends JPanel {
    @Override
    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

canvas.show();

Complete the following tasks:

  • Consult the Graphics documentation for a list of methods that let you draw on a canvas.
  • Use the Graphics2D object to construct a wintry scene of your design. Use the various draw* and fill* methods to accomplish your task. Programmatically draw 3 or more objects of your choosing in various colors.
  • Write a method drawSnowperson that accepts two ints representing the x and y coordinates of a snow person’s base or origin point (and any other parameters you might need). Have the method draw a snow person relative to this base position. Call it multiple times from main so that multiple snow people appear in your scene.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *