Working with Graphics |
Problem: I don't know where to put my drawing code.Problem: The stuff I draw doesn't show up.
- 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 theupdate()
method (although you must still implementpaint()
), as described in Eliminating Flashing.Problem: I'm using the exact same code as a tutorial example, but it doesn't work. Why?
- Check whether your component is showing up at all. Common Component Problems should help you with this.
Problem: How do I draw thick lines? patterns?
- 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()
orupdate()
method, then those two methods might be the only places where the code is guaranteed to work.If you don't see your problem in this list, see Common Component Problems and Common Layout Problems
- 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.
Working with Graphics |