*Edit* Just so you know, we are on the chapter in the book introducing ArrayLists *Edit*
I am having trouble with this problem. The problem is stated:
Implement a class Polygon that contains an array list of Point2D.Double objects. Support methods
public void add(Point2D.Double aPoint)
public void draw(Graphics2D g2)
Draw the polygon by joining adjacent points with a line, and then closing it up by joining the end and start points. Write a graphical application that draws a square and a pentagon using two Polygon objects.
We are given two completed classes called PolygonComponent and PolygonViewer(code below) and have to create one class named Polygon
import javax.swing.JFrame;
public class PolygonViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("PolygonViewer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PolygonComponent component = new PolygonComponent();
frame.add(component);
frame.setVisible(true);
}
}
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
/**
Displays two polygons.
*/
public class PolygonComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Polygon square = new Polygon();
square.add(new Point2D.Double(100, 100));
square.add(new Point2D.Double(100, 150));
square.add(new Point2D.Double(150, 150));
square.add(new Point2D.Double(150, 100));
square.draw(g2);
Polygon pentagon = new Polygon();
double centerX = 200;
double centerY = 200;
double radius = 50;
for (int i = 0; i < 5; i++)
{
double angle = 2 * Math.PI * i / 5;
pentagon.add(new Point2D.Double(
centerX + radius * Math.cos(angle),
centerY + radius * Math.sin(angle)));
}
pentagon.draw(g2);
}
}
The above classes are given and are not to be changed.
Here is what I have written for my Polygon class so far
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class Polygon extends JPanel {
private ArrayList<Point2D.Double> myPolygon = new ArrayList<Point2D.Double>();
private Point2D.Double point;
public void add(Point2D.Double aPoint) {
myPolygon.add(aPoint); // NullPointerException gets thrown here
}
protected void draw(Graphics2D g2) {
for(int i=0; i<myPolygon.size(); i++)
{
g2.draw(myPolygon.getX());
}
}
}
I have spent two evenings on this same problem, rewriting and trying different things and I have hit a wall. I cannot get this thing to draw and I could use some guidance. Obviously my draw method is not working as you see it, I have been going through the java API and cannot seem to get a grasp as to what I need to do.
Thank you in advance for any help!