简体   繁体   English

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

[英]How to initialize a bi-dimensional array of a created object?

I'm trying to initialize a bi-dimensional array of an object that I've created that has a some parameters (x,y,width,height) but doesn't work... The object is just a g.fillOval and when I do the initializing only prints the last object of the array. 我正在尝试初始化我创建的对象的二维数组,该数组具有一些参数(x,y,width,height)但不起作用...该对象只是一个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);
        }
    }

The Oval class: 椭圆形类:

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);
    }
}

All of your classes variables are static 您所有的类变量都是静态的

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

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

This means they are associated with the class Oval .. not a single instance of Oval. 这意味着它们与类Oval ..关联,而不是Oval的单个实例。

Because there is only one copy of each variable, every time you make a new Oval you will overwrite the last value set. 因为每个变量只有一个副本,所以每次创建一个新的Oval时,都会覆盖上一个值集。 When you finally go to draw the Ovals, all of them will be drawn in the exact same spot! 当您最终绘制椭圆形时,所有它们都将在完全相同的位置绘制!

Make them instance variables instead: 使它们成为实例变量:

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

private int x = 0;
private int y = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM