package java2thierry;

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

public class ChangingEllipseFrame extends JFrame {

  public ChangingEllipseFrame() {
    setTitle("Changing Ellipse");
    getContentPane().add(new ChangingEllipsePanel());
  }

  public static void main(String[] args){
    ChangingEllipseFrame frame = new ChangingEllipseFrame();
    frame.setSize(400,150);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.show();
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {}
    CaptureFrameJPEGImage.capture(frame,"changingellipse.jpg");
  }
}

class ChangingEllipsePanel extends JPanel {
  private int width=40;
  private int height=20;
  private Color ellipseColor=Color.black;

  public ChangingEllipsePanel(){
    setBackground(Color.white);

    JButton redButton = new JButton("Red");
    redButton.setBackground(Color.white);
    JButton blackButton = new JButton("Black");
    blackButton.setBackground(Color.white);
    JButton widthButton = new JButton("Width + 2");
    widthButton.setBackground(Color.white);
    JButton heightButton = new JButton("Height + 2");
    heightButton.setBackground(Color.white);

    redButton.addActionListener(new ColorListener(Color.red));
    blackButton.addActionListener(new ColorListener(Color.black));

    widthButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent event){
        width+=2;
        repaint();
      }
    });
    heightButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent event){
        height+=2;
        repaint();
      }
    });

    add(widthButton);
    add(heightButton);
    add(redButton);
    add(blackButton);
  }

  public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    if (width>getWidth()) width=getWidth();
    if (height>getHeight()) height=getHeight();
    Ellipse2D e= new Ellipse2D.Double(
        (getWidth()-width)/2,(getHeight()-height)/2,width,height);
    g2.setPaint(ellipseColor);
    g2.fill(e);
  }

  private class ColorListener implements ActionListener {
    private Color color;

    public ColorListener(Color aColor){
      color=aColor;
    }

    public void actionPerformed(ActionEvent event){
      ellipseColor=color;
      repaint();
    }
  }
}