2013-03-01 146 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