绘制多边形时出现ArrayIndexOutOfBoundsException错误 [英] ArrayIndexOutOfBoundsException error while drawing a polygon
问题描述
我在尝试绘制多边形时遇到了麻烦.首先,当我尝试使用addPoint(int x, int y)
方法绘制多边形并逐个给出坐标时,没有问题,多边形可以完美绘制.但是,如果我将坐标作为数组(x坐标和y坐标的整数数组)给出,则编译器会出错.如您所见,这是工作代码,
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);
}
但是如果我使用xpoints
和ypoints
数组(在Graphics类中为多边形定义),它将无法正常工作.
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.
推荐答案
来自您的评论:
我认为应该是7,因为有7个整数元素 每个数组?
i thought that it should be 7 cause there are 7 integer elements for each array ?
您必须先initialize your array
然后是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;
YPoints同样适用.
Same applies to YPoints as well.
如果您正在寻找动态阵列,请使用 列表 从Java集合框架(如ArrayList)实现类.
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);
...
这篇关于绘制多边形时出现ArrayIndexOutOfBoundsException错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!