Tuesday, September 7, 2010

HW 2: Dice

In this homework you will start with the simple GUI program I provide below and change it so that it displays the side of the dice that the user asks. First, cut-and-paste the program below to a new class called Dice. Run the program and note that it pops up 2 windows: one with an over and the other one with a text box that asks you to enter a number. When you enter a number the horizontal diameter of the oval changes accordingly. Also note that this program is a simple extension of the graphics supplement sections from your textbook.
/** Jose M Vidal 
 * TA Please NOTE: If that's not me on the line above then I deserve 0 points on this homework.

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Dice extends JPanel {
 /** The horizontal diameter of the oval we will draw. */
 public int diameter;
 public void paintComponent(Graphics g) {
  int height = getHeight();
  g.drawOval(0, 0, diameter, height);
 public static void main(String args[]) {
  JFrame frame = new JFrame("An Oval");
  Dice panel = new Dice();
  panel.diameter = 100; //set the diameter of the oval
  frame.setSize(300, 200); //create a window that is 300px horizontally by 200px vertically.
  String diameterPane =
   JOptionPane.showInputDialog("Enter new diameter for the oval:");
  panel.diameter = Integer.parseInt(diameterPane); //set the new diameter
  if (panel.diameter == 0) {
  frame.repaint(); //don't forget to re-paint it!

The program is also here (Dice.java). You will be making many changes to it.
The program you will write will ask the user for the number to display and then display that number in the face of the dice, as shown by the screenshots below.

Note that

  1. your program will continue asking the user for a new number right after displaying the one he just typed,
  2. when the user enters 0 the program should exit.

This program is due Tuesday, September 14 at 9am. Please deposit it in our dropbox or email it to us.

1 comment:

jmvidal said...

A goal of this homework is to get you to learn to read an API (the graphics API in this case) and figure out how to invoke methods you never seen before, like drawing a square. Developers spend a lot of their time reading and understanding new APIs.

In other words, I want you to figure out by yourself how to draw a rectangle. I already showed you how to draw a circle (well, an oval, but if the x-axis equals...do I even need to finish that?)

API: http://en.wikipedia.org/wiki/Application_programming_interface