2014-08-27 72 views
0

我需要一些簡單問題的幫助。我在任務結束時,在那裏我們要製作不同的藝術形象。我製作了一個「正方形內的方塊」框,需要生成該框的4行和4列。堆疊方塊/盒

enter image description here

我認爲最好的辦法是循環的詳細一些,但不能完全使它發揮作用。

我的代碼:

class StandardPanel extends JPanel{  

    public void paintComponent(Graphics g){ 

     Graphics2D g2d = (Graphics2D) g; 

     double alpha = Math.toRadians(5); 
     double factor = 1/(Math.sin(alpha) + Math.cos(alpha)); 
     double size = 200; 

     g2d.translate(size, size); 

     for (int i = 0; i < 28; i++) { 

      int intSize = (int) Math.round(size); 

      g2d.setColor(i % 2 == 0 ? Color.white : Color.white); 
      g2d.fillRect(-intSize/2, -intSize/2, intSize, intSize); 
      g2d.setColor(i % 2 == 0 ? Color.black : Color.black); 
      g2d.drawRect(-intSize/2, -intSize/2, intSize, intSize); 

      size = size * factor; 
      g2d.rotate(alpha); 
     } 
    } 
} 
+2

什麼圖片/它如何不起作用? – Reimeus 2014-08-27 16:56:39

+0

由於即時通訊新的本網站,我不能張貼它的照片呢。但我的方形看起來與此相似: http://www.computing.northampton.ac.uk/~gary/csy3019/images/ShapeSquareSwirl.jpg 現在我只需要生成多達16個並使一個大廣場。 – Chrisaboo 2014-08-27 18:27:38

回答

1

你需要把繪圖代碼在雙嵌套的for循環在網格中創建一個對象的多個。此外,您需要重新翻譯g2d對象,以便它相對於其在網格中的位置實際更改位置:

for (int row = 0; row < 4; row++) // 4 rows 
{ 
    for (int col = 0; col < 4; col++) // 4 columns 
    { 
    g2d.translate(row*size, col*size); // change the location of the object 

    for (int i = 0; i < 28; i++) // draw it 
    { 
     int intSize = (int) Math.round(size); 

     g2d.setColor(i % 2 == 0 ? Color.white : Color.white); 
     g2d.fillRect(-intSize/2, -intSize/2, intSize, intSize); 
     g2d.setColor(i % 2 == 0 ? Color.black : Color.black); 
     g2d.drawRect(-intSize/2, -intSize/2, intSize, intSize); 

     size = size * factor; 
     g2d.rotate(alpha); 
    } 
    } 
} 
+0

您是否複製了我發佈的代碼?雙嵌套for-loop是你原來在代碼中的循環之前的前兩個循環 – elrobe 2014-08-27 21:24:02