2013-05-03 60 views
-4

好的,所以我在編寫這個程序時遇到了問題。我完成了第一部分,但我不知道如何完成它。我嘗試過不同的解決方案和一切,但我仍然沒有線索。這是我到目前爲止。我需要做的就是讓它在四個角落開始。Java中的繪圖線

public void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 
    int width = getWidth(); 
    int height = getHeight(); 
    int number, x, y, dx, dy; 
    x = 0; 
    y = height; 
    number = 15; 
    dx = width/number; 
    dy = height/number; 
    for (int i = 1; i < number; i++) 
    { 
     x += dx; 
     y -= dy; 
     g.drawLine(0, 0, x, y); 
    } 
} 
+1

請正確填寫您的代碼並重寫您的問題。前兩行沒有任何說法,並且「我需要做什麼」的肉詞...很難理解 – leonbloy 2013-05-03 17:39:39

+1

以便在發佈[SSCCE](http://sscce.org/)後立即獲得更好的幫助,簡短,可運行,可編譯的,只是關於JFrame內部的JComponent/JPanel,那麼你的問題將是可回答的 – mKorbel 2013-05-03 17:42:46

+1

你沒有說你的問題是什麼,你試圖去實現什麼。 – 2013-05-03 17:43:26

回答

2

我收集到你想要從每個角向右對角線劃出15條線的扇出。我建議寫一個程序來吸取點的風扇爲任意線段,然後使用:

drawFan(Graphics g, 
     int number,  // number of fan lines 
     int x0, int y0, // coordinates of the point 
     int sx, int sy, // coordinates of the line segment start 
     int ex, int ey) // coordinates of the line segment end 
{ 
    int x = sx, 
     y = sy, 
     dx = (ex - sx)/number, 
     dy = (ey - sy)/number; 
    for (int i = 1; i < number; ++i) { 
     x += dx; 
     y += dy; 
     g.drawLine(x0, y0, x, y); 
    } 
} 

然後,您可以爲每個角落的對角線適當的值進行調用。

public void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 
    int width = getWidth(); 
    int height = getHeight(); 
    drawFan(g, 15, 0, 0, 0, height, width, 0);   // top left corner 
    drawFan(g, 15, 0, height, 0, 0, width, height);  // bottom left corner 
    drawFan(g, 15, width, height, 0, height, width, 0); // bottom right corner 
    drawFan(g, 15, width, 0, 0, 0, width, height);  // top right corner 
} 
0

這裏是解決方案,我的建議是瞭解座標系在Java中的工作原理,這很容易。

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    int widthX = getWidth(); 
    int heightY = getHeight(); 

    int num, i, j; 
    num = 15; 
    i = 0; 
    j = 15; 

    while(i != 16 && j != -1){ 

     g.drawLine(0, 0, widthX*i/num, heightY*j/num); 
     g.drawLine( widthX*i/num, heightY*j/num, widthX, heightY); 
     g.drawLine( widthX*i/num, heightY*i/num, widthX, 0); 
     g.drawLine( widthX*j/num, heightY*j/num, 0, heightY); 

     i++; 
     j--; 

    }//end while 
}//end method paintComponent