堆叠方块/盒

问题描述:

我需要一些简单问题的帮助。我在任务结束时,在那里我们要制作不同的艺术形象。我制作了一个“正方形内的方块”框,需要生成该框的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

你需要把绘图代码在双嵌套的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