We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Returning an array within an object
Page Index Toggle Pages: 1
Returning an array within an object (Read 422 times)
Returning an array within an object
Mar 29th, 2006, 2:36am
 
I'm creating a system of nodes, all of which have the option to contain a list of children nodes to which they connect a red line to. For some reason I can use my push function just fine at the root level to add a new node object to the array of "allnodes", but when I attempt to use it from within a method of the Node object to add to the "children" array, it doesn't seem to work.

Code:
Node[] allnodes = new Node[1];

void setup(){
size(200,200);
smooth();
allnodes[0] = new Node(width/2, 20);
}

void draw(){
background(0);
for(int i=0; i<allnodes.length; i++){
allnodes[i].draw();
}
}

void mousePressed(){
Node newnode = new Node(mouseX, mouseY);
allnodes = push(allnodes, newnode);
allnodes[0].addChild(newnode);
}

class Node{
int x, y;
Node[] children = new Node[0];
Node(int x_, int y_){
x = x_;
y = y_;
}

void draw(){
drawChildLines();
ellipse(x, y, 7, 7);
}

void drawChildLines(){
stroke(255,0,0);
for(int i=0; i<children.length; i++){
line(x, y, children[i].x, children[i].y);
}
noStroke();
}

void addChild(Node newkid){
children = push(children, newkid);
}
}

Node[] push(Node[] n, Node element){
Node[] newn = new Node[n.length+1];
newn[0] = element;
System.arraycopy(n,0,newn,1,n.length);
println(newn.length);
return newn;
}

Node[] pop(Node[] n){
Node[] newn = new Node[n.length-1];
System.arraycopy(n,0,newn,0,n.length-1);
return newn;
}


I'm thinking there is some issue with scope or defining the property as public. I have tried doing so explicity to no affect.
Page Index Toggle Pages: 1