Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance of Graphics ,g , can't be recognized in applen

 
Aaron Law
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am practising on writing my own method in an applet and facting a problem that my own method vertical() & horizontal() can't recognize the Graphics g object.

It's seemed that I can locate the problem but can't solve it. Could u mind to help me to solve the problem? That is:






The follow is a version has no my own method:



Thx.
[ November 09, 2004: Message edited by: Aaron Law ]
 
Jason Fox
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The Reference to Graphics (g) in paint() is currently scoped only to that method. Outside of paint(), the other methods have no idea what g refers to. Two quick ways to fix this would be to either create a global variable that holds a reference to g:


Or, change vertical and horizontal to accept an additional argument of 'Graphics', and then use that reference in each of the methods. Hope this helps.
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That "global" is in quotes, right?
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally, I prefer Jason's second suggestion: add a Graphics object as a parameter to the vertical() and horizontal() methods. Having a "global" Graphics object (technically, it's a instance variable, but that's another topic altogether), means that the Graphics object still has a reference to it after the paintMethod() has finished. There are a couple of problems with this: 1) the object is not eligible for garbage collection and 2) there is the potential for another method to use this "stale" Graphics object outside of the Swing event mechanism. For example, another class could call vertical() or horizontal() directly which would probably have bad results.

Well, I'll quit rambling. Let us know how things work out.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic