// XComponent.java
/*
 Simple class that demonstrates basic drawing,
 using repaint, and layout managers.
*/
import java.awt.*;
import javax.swing.*;
import java.util.*;

import java.awt.event.*;

class XComponent extends JComponent {
	private final static int MAX = 10;
	private int count;	// ranges 1..MAX
	
	XComponent(int width, int height) {
		super();
		setPreferredSize(new Dimension(width, height));
		
		count = 1;
		
		// Create and register a mouse listener
		addMouseListener( new MyMouseListener());
	}
	
	
	// This inner class gets mouse event notifications for us
	class MyMouseListener extends MouseAdapter {
		public void mousePressed(MouseEvent e) {
			upCount();
       		//System.out.println("pressed  x:" + e.getX() + " y:" +e.getY());
		}
	}
	
	/*
	 Increase the count.
	 Call repaint() to signal a redraw --
	 classic example: state change -> repaint
	*/
	public void upCount() {
		count++;
		if (count>MAX) count=1;

		repaint();
	}


	/*
	 Set the count.
	 Does not respect MAX.
	*/
	public void setCount(int count) {
		this.count = count;
		repaint();
	}
		
	/*
	 Draw the series of 1..count rectangles
	*/
	public void paintComponent(Graphics g) {
		//super.paintComponent(g);	// not necessary
		
		int width = getWidth();
		int height = getHeight();
		
		for (int i=0; i<count; i++) {
			// 0/10 1/10 2/10 ...
			int rx = (int) ((float)width*i/(2*count));
			int ry = (int) ((float)height*i/(2*count));
			
			// 5/5 4/5 3/5...
			int rWidth = (int) ((float)width*(count-i))/count;
			int rHeight = (int) ((float)height*(count-i))/count;
			
			g.drawRect(rx, ry, rWidth-1, rHeight-1);
		}
		
		g.setColor(Color.red);
		g.drawString(Integer.toString(count), 20, 20);
	}
	
	public static void main(String[] args) {
		JFrame frame = new JFrame("XComponent");
		JComponent container = (JComponent) frame.getContentPane();
		container.setLayout(new BorderLayout());
		
		// Put an XComponents in the NORTH and CENTER
		container.add(new XComponent(100,100), BorderLayout.NORTH);
		container.add(new XComponent(200, 200), BorderLayout.CENTER);
		
		// Create a little panel (flow layout)
		JPanel panel = new JPanel();
		panel.add(new XComponent(50, 50));
		panel.add(new XComponent(50, 50));
		
		// put it in the SOUTH
		container.add(panel, BorderLayout.SOUTH);
		
		frame.pack();
		frame.setVisible(true);
		
	}
}
