I'm having some problems with a Graphics2D object. My program has lots of drawing methods, so I set up a global Graphics2D object, which I'll just call g2, and then use g2 for all drawing methods throughout the program. This yields unreliable results; it will work well sometimes, and fail other times. I checked and apparently the value of g2 is changed each time the paint() method is called. That should not be a problem: at the beginning of the paint() method, I set g2 to the value of the Graphics object passed into the paint() method. Thus, g2 is always current. But why does it change in the first place? I suspect that my underlying problem lies in my handling of g2. Should I begin every method with
Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D)g;
just to make absolutely sure?
I'd appreciate a pointer to a tutorial on how the Graphics object is altered by Java as the program is running. I've slogged through Oracle's tutorials and they don't help at all.
You can copy a Graphics object; it has a method which I think is called create(). Using that will save you all the trouble of resetting everything; simply let the copy object go out of scope. You will have to look in Graphics and Graphics2D for the method.
OK, I've been going through the tutorial provided by Darryl and 95% of it is old hat to me. The catch is that there was one little fact I never picked up in learning Swing: the notion that all painting must be done through the standard paint() method. It's hard to imagine how I missed that after all these years, but that's what happens when you're self-taught. In any case, I have some major redesign work ahead of me. Thanks for clearing up a blind spot in my knowledge of Java.
Campbell Ritchie wrote:You can copy a Graphics object; it has a method which I think is called create(). Using that will save you all the trouble of resetting everything; simply let the copy object go out of scope.
It's recommended to dispose() any Graphics object you create, to immediately release the system resources associated with it.
(It's equally not recommended to dispose() a Graphics object passed into a painting method as a parameter.)