14.6. The JPanel Component

In the simplest case, you use a JPanel exactly the same as you would a Panel: Allocate the panel, drop components into the panel, and then add the JPanel to a Container. However, JPanel also acts as a replacement for Canvas (there is no JCanvas). When using JPanel as a drawing area in lieu of a Canvas, you need to follow two additional steps. First, you should set the preferred size with setPreferredSize (recall that the preferred size of a Canvas is just its current size, whereas a Panel and JPanel determine their preferred size from the components they contain). Second, you should use paintComponent, not paint, for drawing. And since double buffering is turned on by default, the first thing you normally do in paintComponent ...

Get Core Web Programming, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.