ArrayIndexOutOfBoundsException error while drawing

2019-07-31 10:27发布

问题:

hi there i'm having a trouble while i'm trying to draw a polygon. first of all, when i try to draw a polygon with using addPoint(int x, int y) method and giving coordinates one by one there is no problem, polygon could be drawed perfectly. however, if i give the coordinates as an array (an integer array for x coordinates and y coordinates) compiler gives error. this is the working code as you can see,

@Override
public void paint(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    Polygon poly = new Polygon();

    poly.addPoint(150, 150);
    poly.addPoint(250, 100);
    poly.addPoint(325, 125);
    poly.addPoint(375, 225);
    poly.addPoint(450, 250);
    poly.addPoint(275, 375);
    poly.addPoint(100, 300);

    g2.drawPolygon(poly);

}

but if i use the xpoints and ypoints array (which are defined in Graphics class for polygon) it doesnt work properly.

@Override
public void paint(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    Polygon poly = new Polygon();

    poly.xpoints[0]=150;
    poly.xpoints[1]=250;
    poly.xpoints[2]=325;
    poly.xpoints[3]=375;
    poly.xpoints[4]=450;
    poly.xpoints[5]=275;
    poly.xpoints[6]=100;      

    poly.ypoints[0]=150;
    poly.ypoints[1]=100;
    poly.ypoints[2]=125;
    poly.ypoints[3]=225;
    poly.ypoints[4]=250;
    poly.ypoints[5]=375;
    poly.ypoints[6]=300;

    g2.drawPolygon(poly.xpoints, poly.ypoints, 7);

}

i will appreciate if you can help and thanks anyway.

回答1:

From your comment:

i thought that it should be 7 cause there are 7 integer elements for each array ?

You have to first initialize your array and then populate the array with elements.

    poly.xpoints = new int[7]; // initializing the array
    poly.xpoints[0]=150;       //populating the array with elements.
    poly.xpoints[1]=250;
    poly.xpoints[2]=325;
    poly.xpoints[3]=375;
    poly.xpoints[4]=450;
    poly.xpoints[5]=275;
    poly.xpoints[6]=100;  

Same applies to YPoints as well.

If you looking for a Dynamic Array use one of the List implementing class's from Java collection Framework like ArrayList.

List<Integer> xPoints = new ArrayList<Integer>();
xPoints.add(150);
xPoints.add(250);
...


回答2:

Try and initialize the Polygon using the arrays prebuilt. You can create the arrays before hand and pass them into the constructor for the Polygon.

public Polygon(int[] xpoints, int[] ypoints, int npoints)


回答3:

Do you know what the size of the array is? Is it even initialised?

Quick Google found this:

http://docs.oracle.com/javase/7/docs/api/java/awt/Polygon.html#xpoints http://www.java2s.com/Code/JavaAPI/java.awt/GraphicsdrawPolygonintxPointsintyPointsintnPoints.htm