import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;

/*
 Demonstrates the effects of calling repaint()
 in different ways.
 
 Also demonstrates using some common layout managers
*/
public class Widget extends JComponent {
	private int count;
	
	private static Font font = null;

	public Widget(int width, int height) {
		super();
		setPreferredSize(new Dimension(width, height));
		
		count = 0;
	}

	/*
	 Typical setter -- calls repaint to signal the system.
	*/
	public void setCount(int newCount) {
		if (newCount!=count) {
			count = newCount;
			repaint();
		}
	}
	
	public void increment() {
		setCount(count+1);
	}
	
	/*
	 Draw ourselves with a big font (see the Font class).
	*/
	public void paintComponent(Graphics g) {
		// typical "debug rect" around our bounds just to have
		// something show up
		g.drawRect(0, 0, getWidth()-1, getHeight()-1);
		
		// trick: lazy evaluation of font object
		if (font==null) font = new Font("DIALOG", Font.ITALIC, 96);
		
		g.setFont(font);
		g.setColor(Color.red);
		g.drawString(Integer.toString(count), 4, getHeight()-4);
	}

	
	public static void main(String[] args) {
		JFrame frame = new JFrame("Widget");
		JComponent container = (JComponent) frame.getContentPane();
		container.setLayout(new BorderLayout());
		
		container.add(new JLabel("West"), BorderLayout.WEST);
		container.add(new JLabel("East"), BorderLayout.EAST);

		// A
		// Put things in Panel -- defaults to FlowLayout
		// put panel in north
		final Widget a = new Widget(100, 100);
		JButton button = new JButton("A");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				a.increment();
			}
		});
		
		JPanel panel = new JPanel();
		panel.add(button);
		panel.add(a);
		container.add(panel, BorderLayout.NORTH);


		// B
		// Put things in Box object -- uses BoxLayout
		// put box in CENTER
		final Widget b = new Widget(100, 100);
		button = new JButton("B");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				b.repaint();
				b.increment();
				b.repaint();
			}
		});
		
		Box box = new Box(BoxLayout.Y_AXIS);
		// could call convenience method Box.createVerticalBox()
		box.add(button);
		box.add(b);
		container.add(box, BorderLayout.CENTER);
		
		// C
		// Put things in a panel
		// Set the panel to use BoxLayout
		// Put the panel in the south
		final Widget c = new Widget(100, 100);
		button = new JButton("C");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				c.increment();
				for (int i=0; i<100000000; i++) {}
				c.increment();
			}
		});
		
		panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		panel.add(button);
		panel.add(c);
		container.add(panel, BorderLayout.SOUTH);
		
		frame.pack();
		frame.setVisible(true);
		
	}
		
}
