Here is my solution to HW 2.
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 number the dice is showing. 0 for nothing */
public int number;
/** The radius of the dots in the dice. */
public static final int RADIUS = 10;
/** Draw the dice.
* 50,50 */
public void paintComponent(Graphics g) {
int height = getHeight();
g.setColor(Color.black);
g.drawRect(50, 50, 200, 200); //A 200x200 square offset by 50,50.
switch (number) {
case 0:
break;
case 5: //compiler will optimize these
g.drawOval(100-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top left
g.drawOval(200-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom right
case 3:
g.drawOval(200-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top right
g.drawOval(100-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom left
case 1:
g.drawOval(150-RADIUS, 150-RADIUS, RADIUS*2, RADIUS*2); //center
break;
case 6:
g.drawOval(100-RADIUS, 150-RADIUS, RADIUS*2, RADIUS*2); //center left
g.drawOval(200-RADIUS, 150-RADIUS, RADIUS*2, RADIUS*2); //center right
case 4:
g.drawOval(100-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top left
g.drawOval(200-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom right
case 2:
g.drawOval(200-RADIUS, 100-RADIUS, RADIUS*2, RADIUS*2); //top right
g.drawOval(100-RADIUS, 200-RADIUS, RADIUS*2, RADIUS*2); //bottom left
break;
}
}
/**
* @param args are ignored
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Roll Them Bones");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dice panel = new Dice();
frame.add(panel);
frame.setSize(300, 300); //create a window that is 300px horizontally by 200px vertically.
frame.setVisible(true);
do {
try {
panel.number = Integer.parseInt(JOptionPane.showInputDialog("Enter number for the dice, or 0 to quit:"));
frame.repaint(); //don't forget to re-paint it!
} catch (NumberFormatException e) { //if the user types in something other than an integer, or clicks "cancel"
System.exit(0);
}
}
while (panel.number != 0);
System.exit(0); //without this the program won't end, cse its a GUI program.
}
}
No comments:
Post a Comment