2013-03-01 143 views
1

您好,我在尝试绘制多边形时遇到了麻烦。首先,当我尝试使用addPoint(int x, int y)方法绘制多边形并逐个给出坐标时,没有问题,可以完美地绘制多边形。但是,如果我将坐标作为数组(x坐标和y坐标的整数数组)给出错误。这是工作的代码,你可以看到,ArrayIndexOutOfBoundsException在绘制多边形时出错

@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); 

} 

但如果我使用xpointsypoints阵列(其在图形类中定义的多边形),它不正常工作。

@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); 

} 

我会很感激,如果你能帮助和感谢。

+1

xpoints和ypoints的数组大小是多少? – PermGenError 2013-03-01 21:44:16

+0

我认为它应该是7因为每个数组有7个整数元素? – quartaela 2013-03-01 21:45:27

+0

尝试'poly.xpoints = new int [7]; poly.ypoints = new int [7];' – gefei 2013-03-01 21:46:10

回答

2

从您的评论:

我认为这应该是7病因有7个 每个数组整数元素?

你必须先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。

如果您正在寻找动态数组,请使用List之一实现Java集合框架(如ArrayList)中的类。

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

我认为这个数组是动态定义的,即使当我使用'poly.xpoint.lenght'时它也没有工作。但是,您的解决方案正在为此感谢。 – quartaela 2013-03-01 21:49:27

+1

@quartaela阵列不是动态的。 ArrayList是。 – PermGenError 2013-03-01 21:50:14

+0

@PremGenError'npoints'在你的情况下不会被初始化。你不能只设置数组。看看“多边形”来源。 – jdb 2013-03-01 21:50:49

2

尝试并使用数组初始化的预建的多边形。您可以事先创建数组并将它们传递给Polygon的构造函数。

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

以及我可以使用这种方法,它会更可读:)谢谢 – quartaela 2013-03-01 21:55:07