package graphics.charts;
import gui.ClosableJFrame;
import javax.swing.*;
import java.awt.*;
public class LineGraph extends JComponent
implements Paintable {
private DoubleData dd;
public LineGraph(DoubleData _dd) {
dd = _dd;
setSize(dd.getWidth(), dd.getHeight());
}
public Dimension getPreferredSize() {
return new Dimension(dd.getWidth(), dd.getHeight());
}
public Dimension getMinimumSize() {
return new Dimension(dd.getWidth(), dd.getHeight());
}
public void paint(Graphics g) {
DrawUtil du = new DrawUtil(dd);
Ticks t = new Ticks(dd, getSize());
t.paint(g);
drawGraph(g);
du.drawXAxisLabel(g);
du.drawYAxisLabel(g);
du.drawTitle(g);
System.out.println("Successfully drawing line graphics.graph");
}
private void drawGraph(Graphics g) {
g.setColor(Color.red);
Polygon p = getPolygon();
g.drawPolyline(p.xpoints, p.ypoints, p.npoints);
}
private int[] getXScreenCoords() {
double[] xVals = dd.getXVals();
int xLength = xVals.length;
int width = dd.getWidth();
double deltaX = dd.getDeltaX();
double xOrigin = dd.getXAxisCoord();
double xIncrement = dd.getIncrementNew(xVals, width);
double maxX = dd.getMax(xVals);
int Xs[] = new int[xLength];
if (maxX > 0) {
for (int i = 0; i < xLength; i++) {
Xs[i] = (int) (xIncrement * xVals[i]) + (int) xOrigin;
}
} else {
for (int i = 0; i < xLength; i++) {
Xs[i] = width - ((int) (xIncrement * xVals[i]));
}
}
return Xs;
}
private int[] getYScreenCoords() {
double[] yVals = dd.getYVals();
int height = dd.getHeight();
int yLength = yVals.length;
double deltaY = dd.getDeltaY();
double yIncrement = dd.getYIncrement();
int Ys[] = new int[yLength];
double maxY = dd.getMax(yVals);
double yOrigin = dd.getYAxisCoord();
for (int i = 0; i < yLength; i++) {
Ys[i] = (int) (yOrigin - (yVals[i] * yIncrement)); }
return Ys;
}
private Polygon getPolygon() {
return new Polygon(getXScreenCoords(),
getYScreenCoords(), getXScreenCoords().length);
}
public static void main(String args[]) {
ClosableJFrame cf = new ClosableJFrame();
Container c = cf.getContentPane();
double numberOfPoints = 100;
double eps = (2 * Math.PI + .1) / numberOfPoints;
double theta = 0;
double x[] = new double[(int) numberOfPoints];
double y[] = new double[x.length];
for (int i = 0; i < x.length; i++) {
x[i] = Math.cos(theta);
y[i] = Math.sin(theta);
theta = theta + eps;
}
DoubleData dd = new DoubleData(200, 200);
dd.setXLabel("x label");
dd.setYLabel("y label");
dd.setXVals(x);
dd.setYVals(y);
LineGraph lg = new LineGraph(dd);
c.add(lg);
c.setLayout(
new FlowLayout());
c.setBackground(Color.white);
cf.setSize(200, 200);
cf.setVisible(true);
}
}