Java Graphics not displaying on successive function calls, why?
Posted
by primehunter326
on Stack Overflow
See other posts from Stack Overflow
or by primehunter326
Published on 2010-05-01T07:25:36Z
Indexed on
2010/05/01
7:27 UTC
Read the original article
Hit count: 198
Hi,
I'm making a visualization for a BST implementation (I posted another question about it the other day). I've created a GUI which displays the viewing area and buttons. I've added code to the BST implementation to recursively traverse the tree, the function takes in coordinates along with the Graphics object which are initially passed in by the main GUI class. My idea was that I'd just have this function re-draw the tree after every update (add, delete, etc...), drawing a rectangle over everything first to "refresh" the viewing area. This also means I could alter the BST implementation (i.e by adding a balance operation) and it wouldn't affect the visualization.
The issue I'm having is that the draw function only works the first time it is called, after that it doesn't display anything. I guess I don't fully understand how the Graphics object works since it doesn't behave the way I'd expect it to when getting passed/called from different functions. I know the getGraphics function has something to do with it.
Relevant code:
private void draw(){
Graphics g = vPanel.getGraphics();
tree.drawTree(g,ORIGIN,ORIGIN);
}
vPanel is what I'm drawing on
private void drawTree(Graphics g, BinaryNode<AnyType> n, int x, int y){
if( n != null ){
drawTree(g, n.left, x-10,y+10 );
if(n.selected){
g.setColor(Color.blue);
}
else{
g.setColor(Color.gray);
}
g.fillOval(x,y,20,20);
g.setColor(Color.black);
g.drawString(n.element.toString(),x,y);
drawTree(g,n.right, x+10,y+10);
}
}
It is passed the root node when it is called by the public function. Do I have to have:
Graphics g = vPanel.getGraphics();
...within the drawTree function? This doesn't make sense!!
Thanks for your help.
© Stack Overflow or respective owner