Java创建颜色数组并在形状中使用它们

时间:2013-11-24 02:42:04

标签: java arrays colors

我需要指导课程作业。我目前有一个由红色和蓝色矩形组成的金字塔,我的任务是通过创建各种颜色的数组(确切地说是9)来随机化这些颜色。我在创建阵列时遇到了一些麻烦,因为它不断给我一个错误,我希望有人可以指出我正确的方向让我开始。这是我的代码:我的当前数组是否正确?我把这个数组基于我的教科书中的一个例子,但它似乎没有用。任何帮助将不胜感激。

@SuppressWarnings("serial")
public class Legos2 extends JFrame {
   private int startX;
   private int startY;
   private int legoWidth;
   private int legoHeight;
   private int baseLength;
   private int arcWidth;
   private int arcHeight;

   //Declare and Array of Colors
    Color[] colors;

    //Allocate the size of the array
    colors = new Color[4];

    //Initialize the values of the array
    colors[0] = new Color(Color.red);
    colors[1] = new Color(Color.blue);
    colors[2] = new Color(Color.yellow);
    colors[3] = new Color(Color.green);

   // Constructor
   public Legos2() {
       super("Jimmy's LEGOs");
       startX = 20;
       startY = 300;
       legoWidth = 50;
       legoHeight = 20;
       baseLength = 10;
       arcWidth = 2;
       arcHeight = 2;
   }

   // The drawings in the graphics context
   public void paint(Graphics g) 
   {
       // Call the paint method of the JFrame
       super.paint(g);

       int currentX = startX;
       int currentY = startY;

       //row = 0 is the bottom row
         for (int row = 1; row <= baseLength; row++)
         {  
        currentX = startX;

        System.out.println("row = " + row);

        for (int col = 0; col <= baseLength - row; col++)
        {

            if (col % 2 == 0)
                g.setColor(Color.red);
            else
                g.setColor(Color.blue);

            System.out.println("col = " + col);
            g.fillRoundRect(currentX, currentY, legoWidth, legoHeight, arcWidth, arcHeight);
            currentX = currentX + legoWidth;
        }
        currentY -= legoHeight;
        startX += legoWidth /2;
    }
}
   // The main method
   public static void main(String[] args) {
       Legos2 app = new Legos2();
       // Set the size and the visibility
       app.setSize(550, 325);
       app.setVisible(true);
       // Exit on close is clicked
       app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }
}

2 个答案:

答案 0 :(得分:2)

除了伊兰回答:

你必须导入颜色,图形和JFrame类

import java.awt.Color;

import java.awt.Graphics;

import javax.swing.JFrame;

并指定颜色在构造函数中执行:

public Legos2() {

    colors = new Color[4];

    //Initialize the values of the array
    colors[0] = Color.red;
    colors[1] = Color.blue;
    colors[2] = Color.yellow;
    colors[3] = Color.green;

答案 1 :(得分:0)

您应该在构造函数中初始化数组。 你不能在方法之外初始化它。

public Legos2() {
        //Allocate the size of the array
        colors = new Color[4];

        //Initialize the values of the array
        colors[0] = new Color(Color.red);
        colors[1] = new Color(Color.blue);
        colors[2] = new Color(Color.yellow);
        colors[3] = new Color(Color.green);
...
}
相关问题