Topic: Array of Objects Name: _____________________________________________________ Lab 07: Connect the Dots Period: _______ Date: _______________________ w/ MouseListener Interface Objectives I will implement the MouseListener interface. I will be able to use the Point object. I will be able maintain an array of Points. Point A Point object represents a point on a coordinate plane. It has 2 variables: x and y, The Point object has a 2 argument constructor: Point (int x, int y) Array of Points Create an array of 10 Points called points: Declare and initialize a variable that will indicate where the next Point object will be put into the array: int arrayIndex = 0; Creating a Point and putting it into the points array In mousePressed, create a Point object with the coordinates from the mouse: public void mousePressed (MouseEvent e) { int x = e.getX(); int y = e.getY(); Point pt = new Point(x, y); Put the point into the array, if there is enough space available. If they array is full, print an error message: if (arrayIndex < points.length) { } else System.out.println(“Array is full”); Connecting the Points In paintComponent(Graphics g), we want to draw a line between all the points; Couple things we need to know how to do: 1. How do you traverse the points array and access each Point: for (int k=0; k<arrayIndex; k++) { Point pt1 = points[k]; 2. How do you get the x and y values from a Point int x1 = (int) pt1.getX(); int y1 = (int) pt1.getY(); 3. How do you get the rest of the points starting from the current position (index ): for (int j=k+1; j<arrayIndex; j++) { Point pt2 = points[j]; int x2 = (int)pt2.getX(); int y2 = (int)pt2.getY(); 4. Draw the line between (x1, y1) and (x2, y2) Clear the array when we detect the mouse has exited and reentered the panel. Reallocating the array when it fills up. To clear the array, set the index to 0: arrayIndex=0; When the array is full, we can stop adding new Points or we can create a new array that is larger than the original and copy all the elements. public Point [] reallocate_Point_array (Point [] a) { Point [] b = new Point[a.length*2]; for (int k=0; k<a.length; k++) b[k] = a[k]; return b; } We can then set our reference, points, to the new array: if (arrayIndex >= points.length) points = reallocate_Point_array(points); Changing the color based on the distance between points. When we draw a line between 2 points, we can set the color so that it’s correlated to the distance. In paintComponent( Graphics g ), we’ll set the color to a shade of gray before calling g.drawLine(….) : double distance = computeDistance(x1, y1, x2, y2); int colorVal = (int)(distance * 255 / getWidth()); if (colorVal > 255) colorVal = 255; Color cc = new Color(colorVal, colorVal, colorVal); g.setColor(cc); g.drawLine(x1, y1, x2, y2);