Drawing Random Circles & Squares
/* Draws a circle */
import java.awt.*; import java.applet.Applet; import java.awt.event.*;
public class DrawCircle extends Applet implements ActionListener { Button circleButton, squareButton; int radius = 20; int x, y; int size = 50; int red, green, blue; boolean SQUARE = true; public void init() { x = 200; y = 200; red = green = blue = 0; // Draw the GUI // Create the button circleButton = new Button("Draw Circle"); squareButton = new Button("Draw Square"); // Add it to the applet add(circleButton); add(squareButton); // Add a listener for it circleButton.addActionListener(this); squareButton.addActionListener(this); }// init public void paint(Graphics g) { // set the drawing color to a random color g.setColor(new Color(red, green, blue)); if (SQUARE == false) { // paint a circle drawCircle(g, x, y, radius); } else { // paint a square drawSquare(g, x, y, size); } // print out the values of x, y, and r System.out.println("x="+x+", y="+y+", radius="+radius); g.drawString("x="+x+", y="+y+", radius="+radius, 10, 390); } //paint // Listener for button public void actionPerformed(ActionEvent e) { // Decide which button was pressed if (e.getSource() == circleButton) { // circle button was pressed SQUARE = false; } else { // square button was pressed SQUARE = true; } // pick a random color red = (int) (Math.random()*256); green = (int) (Math.random()*256); blue = (int) (Math.random()*256); // Assign random values to x, y, and radius // Ensure that x, y is within the bounds of the applet (400x400) x = (int) (Math.random()*400); y = (int) (Math.random()*400); radius = (int) (Math.random()*100); size = (int) (Math.random()*200); repaint(); } // actionPerformed private void drawSquare(Graphics g, int x, int y, int w) { // Draw a square on g with top-left corner at x, y and side w g.fillRect(x, y, w, w); } // drawSquare private void drawCircle(Graphics g, int x, int y, int r) { // Draw a circle on g centered at x, y and radius, r g.fillOval(x-r, y-r, 2*r, 2*r); } // drawCircle } // DrawCircle