Using a button to draw random dots


/*
	A simple Java applet that illustrates the use of buttons and also
	the use of Math.random function to generate random numbers.
	
	The applet draws a random sized filled-circle at a random place
	in the applet window, in a random color, each time the button is pressed.
	
*/

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class randomDots extends Applet implements ActionListener
{
	Button drawButton;
	
	public void init() {
		
		// create the button widget
		drawButton = new Button("Draw");
		
		// add it to the applet gui
		add(drawButton);
		
		// register a listener for the button
		drawButton.addActionListener(this);
		
	} // end of init
	
	public void paint( Graphics g ) {
		int x, y, r;
		
		// generate a random point to be the center of the circle
		// restrict it to beween 0 and 200 (the size of the applet window)
		x = (int) (Math.random()*200);
		y = (int) (Math.random()*200);
		
		// select a random size of the radius (make it in the range 10..40)
		r = 10 + (int)(Math.random()*30);
		
		// draw the circle
		drawCircle(g, x, y, r);
		
		System.out.println("repainting" + x + y + r);
	} // end of paint
	
	private void drawCircle(Graphics g, int x, int y, int r) {
		// draws a circle at x,y of radius r in the graphics window g
		// chooses a random color for it as well
		int red, green, blue;
		
		// choose the rgb values
		red = (int) (Math.random() * 256);
		green = (int) (Math.random() * 256);
		blue = (int) (Math.random() * 256);
		
		// set the foreground to the seledted color
		g.setColor(new Color(red, green, blue));
		
		// draw the ciclre
		g.fillOval(x-r, y-r, 2*r, 2*r);
	} // end of drawCircle
	
	public void actionPerformed(ActionEvent e) {
	
		// Nothing much to do here except repaint, for now
		if (e.getSource() == drawButton)
			repaint();
	} // end of actionPerformed
} // end of applet