import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class CubicPanel extends JPanel {
    Grid grid;
    CubicFunction function;
    AffineTransform transform;
    int width = 0, height = 0;
    BoundingBox bbox;
    
    public CubicPanel(double llx, double lly, double urx, double ury) {
        setBackground(Color.white);
        bbox = new BoundingBox(llx, lly, urx, ury);
        grid = new Grid(this);
        function = new CubicFunction(this);
    }

    public void paintComponent(Graphics gfx) {
	super.paintComponent(gfx);
        Rectangle size = getBounds();
        Graphics2D g = (Graphics2D) gfx;
        if (size.width != width || size.height != height) {
            width = size.width;  height = size.height;
            float ratioX = (float) (width / (bbox.urx - bbox.llx));
            float ratioY = (float) (-height /(bbox.ury - bbox.lly));
            transform = new AffineTransform();
            transform.scale(ratioX, ratioY);
            transform.translate(-bbox.llx, -bbox.ury);
        }
        grid.plot(g);
        function.plot(g);
    }

    public BoundingBox getBoundingBox() {
	return bbox;
    }

    public AffineTransform getTransform() {
	return transform;
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("CubicPanel");
	frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        CubicPanel cubic = new CubicPanel(-2, -3, 2, 3);
        frame.getContentPane().add(cubic, BorderLayout.CENTER);
        cubic.setPreferredSize(new Dimension(300, 300));
        frame.pack();
        frame.show();
    }    
}

