import java.awt.Frame; import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.Graphics2D; // Used for anti-aliasing import java.awt.RenderingHints; // Used for anti-aliasing public class GraphicsDiceWithFrame { public static void main(String[] args) { // Create a frame, set the size of the frame, and have the // frame appear in the center of the screen Frame frame = new Frame(); frame.setSize(314, 198); frame.setLocationRelativeTo(null); // Create (instantiate) an instance of the 'DiceCanvas' class // and set its background color to black DiceCanvas canvas = new DiceCanvas(); canvas.setBackground(Color.black); // Add the canvas to the frame and make the frame visible frame.add(canvas); frame.setVisible(true); // Close and destroy the window (frame) when a closing event is // detected; without this section of code, it can be difficult // for a user to end the program and make the frame go away frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); System.exit(0); } }); } } // The 'DiceCanvas' class becomes a type of canvas since it extends // the 'Canvas' class class DiceCanvas extends Canvas { // Display the graphics, text, and image in the frame public void paint(Graphics g) { // This line causes graphics and text to be rendered with anti-aliasing // turned on, making the overall display look smoother and cleaner ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setColor(Color.white); // Set the color for the dice g.fillRect(56, 48, 75, 75); // Create die #1 g.fillRect(176, 48, 75, 75); // Create die #2 int valueDie1 = (int) (Math.random() * 6) + 1; // Choose a random die #1 value int valueDie2 = (int) (Math.random() * 6) + 1; // Choose a random die #2 value g.setColor(Color.red); // Set the color for the dice text g.setFont(new Font("Helvetica", Font.BOLD, 76)); // Set the dice text font and size g.drawString(Integer.toString(valueDie1), 71, 112); // Display the die #1 value g.drawString(Integer.toString(valueDie2), 191, 112); // Display the die #2 value } }