Reputation: 1
I have been under the impression that a Canvas or a JPanel were necessary to put graphics on a JFrame, however I saw a video earlier in which the person was using paint(graphics g)while extending JFrame and hadn't made a panel or a canvas. If this is a case, why do people bother with making a Canvas or a JPanel?
Upvotes: 0
Views: 274
Reputation: 347194
JFrame
extends from Frame
, which extends from Window
, which extends from Container
, extends from Component
which defines paint
.
If this is a case, why do people bother with making a Canvas or a JPanel?
To answer that question, you need to have a better understanding of JFrame
(and window based classes).
JFrame
is actually a composite component, that is, it's made of a number of other components which provide the core functionality of the window
What this means is, if you override paint
and perform custom painting on the frame, it's very possible that you will paint over the child components or the child components will paint over it, and because of the way the paint subsystem works, will do so any time without the frame's paint method been called.
Frame's include the window decorations within their available area. This means that the "viewable" area is actually smaller then the defined area of the frame.
This is also why it's recommend to use pack
instead of setSize
This means that if you override paint
you could actually paint under the window decorations (yes, this happens all the time, and we're tired of answering it)
Screen shot from How can I set in the midst?
The contentPane
of JFrame
takes care of this, as it's laid out within the viewable area.
Top level containers, like JFrame
aren't double buffered, so, even if you overcome all of the above, you will get updates which flicker. Sure you could "devise" you're own double buffering algorithm, but in Swing (ie JPanel
), it's free, so why bother
As a general recommendation, we generally discourage extending from JFrame
(or other top level containers) as it locks you into a single use case and prevents the possibility of re-use.
On the other hand, if you use a JPanel
, you can add it to what ever container you want, when ever you want
Upvotes: 7