简体   繁体   中英

Initializing java.awt.geom.Point2D

I am developing using Java SE on NetBeans 7.3.1 on Windows 7. I write the following code.

import java.awt.geom.Point2D;

static void setDisplayParams(Vector<Point2D> coords, double xMin, double xMax, double yMin, double yMax){
    Point2D newCoords, oldCoords;
    Vector<Point2D> displayCoords = new Vector<Point2D>();

    for (int i=0; i<coords.size(); ++i){
                oldCoords=coords.elementAt(i);
                newCoords.setLocation(oldCoords.getX(), yMax-oldCoords.getY());
                displayCoords.add(newCoords);
    }
}

At the line

newCoords.setLocation(oldCoords.getX(), yMax-oldCoords.getY());

I get the message

variable newCoords might not have been initialzed

I Googled

java.awt.geom.Point2D initializing java

and read here that

Point2D.Double()

is supposed to initialize a java.awt.geom.Point2D variable. However newCoords does not have a field Double.

My for loop was initially

                for (int i=0; i<coords.size(); ++i){
                newCoords=coords.elementAt(i);
                newCoords.setLocation(newCoords.getX(), yMax-newCoords.getY());
                displayParams.displayCoords.add(newCoords);
            }

This did not give me any error messages but it changed the values in coords which I do not want to do.

You use a static reference like this.

for (int i=0; i<coords.size(); ++i){
    newCoords=coords.elementAt(i);
    displayParams.displayCoords.add(new Point2D.Double(newCoords.getX(), yMax-newCoords.getY()));
}

This will create a new Point2D and leave our newCoords (element in the array) object unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM