如何初始化创建对象的二维数组?

时间:2016-09-22 15:50:28

标签: java arrays object canvas jframe

我正在尝试初始化我创建的具有一些参数(x,y,宽度,高度)的对象的二维数组但是不起作用...对象只是一个g .fillOval,当我进行初始化时,只打印数组的最后一个对象。

Ovals = new Oval[4][4];
        for (int y = 0; y < 4; y++) {
            for (int x = 0; x < 4; x++) {
                Ovals[x][y] = new Oval(x*100, y, 30,30);
            }
        }

...

for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            Ovals[x][y].paint(g);
        }
    }

Oval课程:

package objectes;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class Oval extends Canvas{

    private static Random random;

    private static int r1 = 0;
    private static int r2 = 0;

    private static int x = 0;
    private static int y = 0;
    private static int randomN = 5;

    public static int color; //0 = red(#FF5C5C), 1 = blue(#4097ED), 2 = green(#65EB8F), 3 = yellow(#F5F267), 4 = orange(#FFAD42)

    public Oval(int x, int y, int r1, int r2) {
        //Constructor
        this.x = x;
        this.y = y;
        this.r1 = r1;
        this.r2 = r2;

        random = new Random();
        randomN = random.nextInt();
        if (randomN < 0 ) {
            randomN = randomN*-1;
        }
        randomN = randomN % 5;
    }

    public void paint(Graphics g) {
        switch (randomN) {
        case 0: 
            g.setColor(Color.decode("#ff5C5C"));
            break;
        case 1:
            g.setColor(Color.decode("#4097ed"));
            break;
        case 2:
            g.setColor(Color.decode("#65eb8f"));
            break;
        case 3:
            g.setColor(Color.decode("#f5f267"));
            break;
        case 4:
            g.setColor(Color.decode("#ffad42"));
            break;
        }
        g.fillOval(x, y, r1, r2);
    }
}

1 个答案:

答案 0 :(得分:0)

所有类变量都是静态的

EntityTypeConfiguration

这意味着它们与类private static int r1 = 0; private static int r2 = 0; private static int x = 0; private static int y = 0; 相关联..而不是单个Oval实例。

因为每个变量只有一个副本,所以每次创建新的Oval时,都会覆盖最后一个值集。当你最终绘制椭圆形时,所有这些都将被绘制在完全相同的位置!

改为使用实例变量:

Oval