So I made an extension of a JPanel called MyCanvas and it performs just as I want. However I realized that I don't plan on adding JComponents to a MyCanvas, so I thought it would be better to extend a JComponent instead.
Unfortunately when I extend a JComponent it doesn't paint the background. I found out that (by reading this) it's recommended to use a JPanel instead.
Because I'm curious individual I looked up the Source Code of JPanel and I don't see where it paints the background, hence it should possible to paint the background using a JComponent.
It is true? Can the JComponent paint the background? Or should I stick we extending a JPanel?
First somebody said plainly that JComponent doesn't paint its background. And then you put together a small piece of test code which proved that was the case. Good work. So what more do you want?
You can't find anything in JPanel's source code which paints the background, because that sort of thing is done by the PanelUI object which does the rendering for whatever the current look-and-feel is.
And yes, JPanel is the standard replacement for the old AWT Canvas class.
Paul Clapham wrote:First somebody said plainly that JComponent doesn't paint its background. And then you put together a small piece of test code which proved that was the case. Good work. So what more do you want?
You can't find anything in JPanel's source code which paints the background, because that sort of thing is done by the PanelUI object which does the rendering for whatever the current look-and-feel is.
Well I'm a curious and stubborn individual. If someone tells me something is impossible then I want make sure I understand why that is. But what you've said about the PanelUI does explain quite well. Many thanks :)
I think you mis-understood me Rob if I mod your code as such and run it using a transparent PNG image I get a Red image and a Not-blue image.
I've checked the Swing code a bit, and the cause is the lack of a UI class. JPanel has BasicPanelUI as its UI, whereas JComponent has none.
JComponent.paintComponent calls update(Graphics, Component) on it's UI (if there is one). The default of that is this:
You can get the same behaviour by changing the JComponent subclass' paintComponent to this:
That's one approach. There is one even better - use the pluggable look&feel (plaf) mechanism properly:
This is the basic approach for creating JComponent sub classes. I myself have created a few successfully this way; that's also why the JCanvas class has comments - those are copied (and slightly modified) from one of my own component classes.