Heavy vs light weight
Basically speaking, a heavy weight component is linked to its own native peer, where light weight components share a common native peer.
In general, it’s not a good idea to mix heavy and light weight components as there are issues with the z-order and in my experience (even though it’s supposed to be better now) there are painting issues that can crop up.
This is the reason why you have been discouraged from using the Canvas
class, probably because you were trying to place it onto a light weight component…I guess
The illusion of control
One of the biggest issues for newcomers to the Swing API is the illusion that you have some kind of control over the painting process, you don’t. It’s easier to just accept it.
The best you can do is request that the repaint manager perform an update at its earliest convenience.
Also, calling getGraphics
is not guaranteed to return a non-null value.
The correct order of things
paint
vs paintComponent
The problem here is paint
does a number of important jobs, calling paintComponent
is just one of them.
In Swing we are greatly encouraged to use paintComponent
whenever we want to perform custom painting, this is, generally, the lowest level on the component and is called before the child components are painted.
If you override paint
and then paint on the Graphics
after the call to super.paint
you will end up painting on top of everything, this isn’t always the desired result
Even if it were, child components can be painted independently of their parent container, making the paint “over” any paint effects you might have added
Useful links
- Painting in Swing (talks about the how the paint process works)
- Performing Custom Paining (in Swing)
- 2D Graphics Trail
Parting thoughts
Only components that are actually added to a component, which is attached to a native peer will ever have there paint
method called. So trying to paint to a component that hasn’t been added to a container yet is rather pointless…