如何获得for循环增量高度和pos

时间:2014-05-18 18:50:25

标签: java paintcomponent

我正在努力让我的drawRect在面板上创建13次。这可以正常工作,但我还希望它从说100的高度开始,并递增到550。我不知道如何添加高度的增量,因为我已经在for循环中使用了draw rect。

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.Random;

import javax.swing.JPanel;

public class Draw extends JPanel
{
    Color rand;

    private int randRed() {
        int red;
        Random randomNumber = new Random();
        red = randomNumber.nextInt(255);
        return red;
    }

    private int randGreen() {
        int green;
        Random randomNumber = new Random();
        green = randomNumber.nextInt(255);
        return green;
    }

    private int randBlue() {
        int blue;
        Random randomNumber = new Random();
        blue = randomNumber.nextInt(255);
        return blue;
    }

    int newRectPos = 0;
    public void paintComponent(java.awt.Graphics g)
    { 
        super.paintComponent(g);

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

        }

        for (int j = 0; j <= 800; j = j + 60; int i = 0; i <= 550; i ++)
        {
            g.setColor(new Color(randRed(), randGreen(), randBlue()));
            g.drawRect(j, 0, 60, 550);
            g.fillRect(j, 0, 60, 550);
            repaint();

        }
    }
}

2 个答案:

答案 0 :(得分:1)

而不是

  

for(int j = 0; j&lt; = 800; j = j + 60; int i = 0; i&lt; = 550; i ++)

你可以写

for (int j = 0; j <= 800 && j <= 550; j += 60, i ++)

或作为

的嵌套循环
for (int j = 0; j <= 800; j = j + 60) 
    for(int i = 0; i <= 550; i ++)

答案 1 :(得分:1)

您可以在for循环语句的第一部分中定义多个变量,并用逗号,分隔:

for (int i = 0, j = 0;  //variable definition, more than 1 from the same type
     j <= 800 && i <= 550; //conditional
     j += 60, i ++ //after completing a loop in the for
    ) {
        g.setColor(new Color(randRed(), randGreen(), randBlue()));
        //fix this code accordingly
        g.drawRect(j, 0, 60, 550);
        g.fillRect(j, 0, 60, 550);
        repaint();
}