//-------------------------------------------------------------------------------------------------
//
// MovingGraphicsComponent2.java
//
// written by:    Simon Parsons
// last modified: 6th September 2012
//

// An object that draws a number of ellipses on the screen. Based on
// the examples from "Learning Java" by Niemeyer and Knudsen, page 49-51 and
// page 694.

import java.awt.*;                                                 // Use the awt library
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;                                              // Use the swing library
import java.util.Random;                                           // Get random numbers

// The Moving Component class is a subclass of JComponent and defines an object that listens
// for actions (in this case multiple button presses).

public class MovingGraphicsComponent2 extends JComponent 
	implements ActionListener
{   
	JButton buttons[]; 
        	
	int count = 0;
	
	// Set up buttons and add a listener for each
	
	public MovingGraphicsComponent2() {
		buttons = new JButton[5];
		buttons[0] = new JButton("1");
		buttons[1] = new JButton("2");
		buttons[2] = new JButton("3");
		buttons[3] = new JButton("4");
		buttons[4] = new JButton("5");
		
		setLayout(new FlowLayout()); 
		for(int i=0; i<5; i++){
			add(buttons[i]);
			buttons[i].addActionListener(this);
		}	
	}
	
	// How to paint the ellipse elements. There are count ellipses
	// so create them, put them at random locations and make them yellow.
	
	public void paintComponent(Graphics g){               
		Graphics2D g2 = (Graphics2D)g;                    
		Shape shapes[] = new Shape[count];
		g2.setPaint(Color.white);
		Random randomGenerator = new Random();

		for(int i=0; i < count; i++){
			int newX = randomGenerator.nextInt(200);
			int newY = randomGenerator.nextInt(200);
			shapes[i] = new Ellipse2D.Float(50+newX, 50+newY, 100, 50);        
			g2.setPaint(Color.red);
			g2.fill(shapes[i]);
		}
	}
	
	// Set the value of count to reflect which button was pressed.
	
	public void actionPerformed(ActionEvent e){       
		if(e.getSource() == buttons[0]){
			count = 1;
		}
		if(e.getSource() == buttons[1]){
			count = 2;
		}
		if(e.getSource() == buttons[2]){
			count = 3;
		}
		if(e.getSource() == buttons[3]){
			count = 4;
		}
		if(e.getSource() == buttons[4]){
			count = 5;
		}
	    repaint();
	}
}