teaching machines

CS 148 Lab 5 – More Methods

October 2, 2019 by . Filed under cs1, cs148, fall 2019, labs.

Welcome to lab 5!

If you have checkpoints from the last lab 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.

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. Your next task is to use the Graphics2D class to programmatically draw a scene.

Open your IntelliJ project and create a package named labs.lab05. With the lab05 package selected, paste in the class Canvas listed below. IntelliJ will automatically create the class for you.

package labs.lab04;

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

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

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

    SwingUtilities.invokeLater(() -> {
      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() {
    SwingUtilities.invokeLater(() -> {
      frame.setVisible(true);
    });
  }
  
  private class CanvasPanel extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
      g.drawImage(image, 0, 0, null);
    }
  }
}

This class pops open a window to view an image. Do not modify it in any way; your other code will construct an instance of it.

Create in a separate file a class named Scene 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: