Common Graphics Problems (and Their Solutions)
Problem:
I don't know where to put my drawing code.
- Drawing code belongs in the
paint() method
of a custom component.
You can create a custom component
by creating a subclass of the Canvas, Panel, or Applet class.
See
How to Use Canvases
for information on implementing a custom component.
For efficiency, once you have your drawing code working,
you can modify it to go in the update() method
(although you must still implement paint()),
as described in
Eliminating Flashing.
Problem:
The stuff I draw doesn't show up.
Problem:
I'm using the exact same code as a tutorial example,
but it doesn't work.
Why?
- Is the code executed in the exact same method as the tutorial example?
For example, if the tutorial example has the code in the example's
paint() or update() method,
then those two methods might be the only places
where the code is guaranteed to work.
Problem:
How do I draw thick lines? patterns?
- The AWT's API for primitive graphics is currently rather limited.
For example, it supports only one line width.
You can simulate thick lines by drawing multiple times
at one-pixel offsets or by drawing filled rectangles.
Also, the AWT doesn't currently support fill or line patterns.
If you don't see your problem in this list, see
Common Component Problems
and
Common Layout Problems