Jofre Vallès Jofre Vallès - 2 months ago 4
Java Question

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.

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

Answer

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.

Because there is only one copy of each variable, every time you make a new Oval you will overwrite the last value set. 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;