File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Instance of Graphics ,g , can't be recognized in applen Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Instance of Graphics ,g , can Watch "Instance of Graphics ,g , can New topic

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

Aaron Law

Joined: Nov 09, 2004
Posts: 3
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:

[ November 09, 2004: Message edited by: Aaron Law ]
Jason Fox
Ranch Hand

Joined: Jan 22, 2004
Posts: 114

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

Joined: Jul 30, 2003
Posts: 805
That "global" is in quotes, right?

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Instance of Graphics ,g , can't be recognized in applen
jQuery in Action, 3rd edition